swift - 设置前景色仅对 NSAttributedString 有效一次

标签 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)

最佳答案

来自 setAttributes() 的文档:

These new attributes replace any attributes previously associated with the characters in 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。第二个不会出现这个问题。

关于swift - 设置前景色仅对 NSAttributedString 有效一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48318561/

相关文章:

swift - 由于信号 : Segmentation fault: 11 when set attributedString,命令失败

Xcode Swift 初始 View 大小不正确

ios - 在需要从数据库计算的值时如何对 NSFetchedResultsController 更新使用react?

swift - 为按钮赋予值 - Swift

ios - NSAttributedString 在 tableViewCell 中滚动不流畅(消失/重新出现)

ios - 如何为 UITextView Swift 添加下划线/粗体/斜体能力

快速错误: Consecutive declarations on a line must be separated by ';'

ios - Swift - NSDateFormater 不工作

ios - 在 TextView iOS 中的属性字符串末尾添加一个 nsstring

ios - UITextView 在 iPhone 5/5s 上切断文本,但在 iPhone 6 上没有