【问题标题】:Apply different attributes on UILabel.attributedText on the go随时随地在 UILabel.attributedText 上应用不同的属性
【发布时间】:2018-02-20 23:19:00
【问题描述】:

我正在使用带有 Xcode 9.2 的 Swift 4。

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

由于使用append() 我将所有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 随时切换它们是否是一个不错的解决方案(虽然不是最佳解决方案)?

谢谢!

【问题讨论】:

标签: ios swift uilabel nsattributedstring


【解决方案1】:

试试这个

     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;

【讨论】:

  • 我在创建和附加 NSMutableAttributedStrings 时没有问题,事实上我的代码在这方面工作得很好。我的问题是如何知道属性已应用于字符串的位置,并随时删除/恢复它们
  • 您可以将范围设置为字符串并将最终字符串附加到可变对象。像“ [mutableAttStr addAttribute:str value:[UIColor grayColor] range:NSMakeRange(0, str.length)]”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-07
  • 2016-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多