对于NSAttributedString,设置前景色仅适用一次

时间:2018-01-18 10:03:28

标签: swift nsattributedstring

字符串的手机部分获取下划线属性,但颜色仍为红色。我已将颜色分开并强调setAttributes()调用,以便清楚地表达,同时在一次调用时也会发生这种情况。

    let text = "call "
    let phone = "1800-800-900"

    let attrString = NSMutableAttributedString(string: text + phone, attributes: nil)
    let rangeText = (attrString.string as NSString).range(of: text)
    let rangePhone = (attrString.string as NSString).range(of: phone)

    attrString.setAttributes([NSAttributedStringKey.foregroundColor: UIColor.red],
                             range: rangeText)

    attrString.setAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue],
                             range: rangePhone)

    attrString.setAttributes([NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue],
                             range: rangePhone)

2 个答案:

答案 0 :(得分:3)

来自setAttributes()的文件:

  

这些新属性会替换之前与之关联的任何属性   aRange中的字符。

换句话说,它会替换它们,删除之前设置的所有内容,因此当您添加下划线时,它会删除该范围内的颜色。

解决方案,使用addAttributes()代替setAttributes()

let text = "call "
let phone = "1800-800-900"

let attrString = NSMutableAttributedString(string: text + phone, attributes: nil)
let rangeText = (attrString.string as NSString).range(of: text)
let rangePhone = (attrString.string as NSString).range(of: phone)

attrString.addAttributes([NSAttributedStringKey.foregroundColor: UIColor.red],
                         range: rangeText)

attrString.addAttributes([NSAttributedStringKey.foregroundColor: UIColor.blue],
                         range: rangePhone)

attrString.addAttributes([NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue],
                         range: rangePhone)

其他解决方案,请使用两个NSAttributedString(我也会删除枚举中的NSAttributedStringKey

let textAttrStr = NSAttributedString(string:text, attributes:[.foregroundColor: UIColor.red])
let phoneAttrStr = NSAttributedString(string:phone, attributes:[.foregroundColor: UIColor.blue,
                                                               .underlineStyle: NSUnderlineStyle.styleSingle.rawValue])

let finalAttrStr = NSMutableAttributedString.init(attributedString: textAttrStr)
finalAttrStr.append(phoneAttrStr)

第一种解决方案可能存在问题:
range(of:)仅返回第一次出现的范围。 换句话说,如果text =“1800”和phone =“18”,您将收到不需要的结果。因为rangePhone将来自索引0到1,而不是1800 18中的7到8。这个问题不会发生在第二个问题上。

答案 1 :(得分:0)

不应该分开 setAttributes的第二次和第三次调用,因为后者会覆盖之前的。将样式组合在一个数组中:

attrString.setAttributes([.foregroundColor: UIColor.blue,
                          .underlineStyle: NSUnderlineStyle.styleSingle.rawValue],
                          range: rangePhone)

<强>结果:

screenshot of the result