我正在使用swift 4,xcode 9.2。
我有一个UILabel
,在其.attributedText
属性中,我已经关联了NSMutableAttributedString
。实际上,此 NSMutableAttributedString
是由两个不同 NSMutableAttributedString
的串联制成的,每个属性不同。
由于使用append()
i将所有NSMutableAttributedString
合并到一个可突变的字符串中,因此如何在附加所有内容之前检索我先前设置的属性范围(可能无法完成(?或者,有一种方法可以放置比UILabel.attributedText
内的NSMutableAttributedString
多?或者,再次,我可以在不使用UILabel
的情况下获得此行为(例如,也许使用UITextView
(?
这是我遇到的问题,因为我需要添加隐藏 UISwitch
(=将其恢复为默认为黑色(,并在旅途中再次显示此NSMutableAttributedString
的foregroundColor
,但是由于此字符串的一部分只有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;