gpt4 book ai didi

ios - 随时随地在 UILabel.attributedText 上应用不同的属性

转载 作者:行者123 更新时间:2023-11-28 07:53:48 24 4
gpt4 key购买 nike

我使用的是 Swift 4 和 Xcode 9.2。

我有一个 UILabel,在它们的 .attributedText 属性中我关联了一个 NSMutableAttributedString。事实上,这个NSMutableAttributedString是由两个不同的NSMutableAttributedString拼接而成的,每个都有不同的属性。

自从使用 append() 我将所有 NSMutableAttributedString 合并到一个可变字符串中,我如何才能在附加所有内容之前检索我之前设置的属性范围(可能它不能完成)?或者,有一种方法可以在 UILabel.attributedText 中放置多个 NSMutableAttributedString 吗?或者,我能否在不使用 UILabel(例如,可能使用 UITextView)的情况下获得此行为?

这是我遇到的问题,因为我需要添加一个隐藏(=将其恢复为默认黑色)并再次显示此 foregroundColorUISwitch NSMutableAttributedString 正在运行,但由于该字符串只有一部分具有 foregroundColor 属性,我不能简单地将属性应用于整个字符串。

这是代码:

func attributedTest (_ testString : String)
{
// the first NSMutableAttributedString created
let firstString = NSMutableAttributedString(
string: testString,
attributes: [NSAttributedStringKey.font : UIFont(
name: "Futura",
size: 20.0)!])

// the second NSMutableAttributedString created, they're equal
let secondString = NSMutableAttributedString(
string: testString,
attributes: [NSAttributedStringKey.font : UIFont(
name: "Futura",
size: 20.0)!])

// here I'm adding the attributed on test2
// the NSRange, in this case, is equal to the whole string
secondString.addAttribute(NSAttributedStringKey.foregroundColor, value: UIColor.red, range: NSRangeFromString("0, \(testString.count)"))

// here I'm appending the second string to the first one
firstString.append(secondString)

// here I'm setting the testLabel.attributedText
testLabel.attributedText = test
}

我想到了这个 NSMutableAttributedString 的普通副本,根本没有任何属性(UIFont 在属性之外,所以我不担心),存储在某处.拥有这两个字符串并在需要时通过 UISwitch 随时切换它们是否是一个不错的解决方案(虽然不是最优的)?

谢谢!

最佳答案

试试这个

     NSMutableAttributedString *mutableAttStr = [[NSMutableAttributedString alloc] init];
NSString *str = @"your string here";
NSDictionary *attributes = @{NSForegroundColorAttributeName : [UIColor redColor]};
NSAttributedString *newAttStr = [[NSAttributedString alloc] initWithString:str attributes:attributes];
[mutableAttStr appendAttributedString:newAttStr];
testLabel.attributedText = mutableAttStr;

关于ios - 随时随地在 UILabel.attributedText 上应用不同的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48895788/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com