【问题标题】:Changed color of a substring but the font setting is reset更改了子字符串的颜色,但重置了字体设置
【发布时间】:2017-02-07 15:31:22
【问题描述】:

How to change color of text stirngs inside UITextView in Swift3

我尝试像这样引用上面的 url 来更改子字符串的颜色。

func textViewDidChange(_ textView: UITextView, pageIndex: Int) {
    let attrStr = NSMutableAttributedString(string: textView.text)
    let inputLength = attrStr.string.characters.count
    let searchString = self.emphasisingWordList[pageIndex]
    let searchLength = searchString.characters.count
    var range = NSRange(location: 0, length: attrStr.length)

    while (range.location != NSNotFound) {
        range = (attrStr.string as NSString).range(of: searchString, options: [], range: range)
        if (range.location != NSNotFound) {
            attrStr.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSRange(location: range.location, length: searchLength))
            range = NSRange(location: range.location + range.length, length: inputLength - (range.location + range.length))
            textView.attributedText = attrStr
        }
    }
}

但是,我发现设置属性文本后,字体大小和颜色会重置为默认值(黑色)。

我在代码末尾添加了这些行,但整个字符串当然会受到影响。

self.sloganTextView.font = UIFont.systemFont(ofSize: 35)
self.sloganTextView.textColor = UIColor.white

有什么好的解决办法还是得把每个属性颜色一个一个改?

正如许多人已经提到的,selectable 设置为 true。

【问题讨论】:

    标签: ios swift swift3 uitextview


    【解决方案1】:

    你可以试试这个代码:

    var strName: String = "ABC"
    var strTitle: String = "XYZ"
    let commentString = NSMutableAttributedString(string: strTitle + " \(strName)")
    commentString.addAttribute(NSForegroundColorAttributeName, value: UIColor.blue, range: NSRange(location: 0, length: (strTitle.characters.count )))
    commentString.addAttribute(NSForegroundColorAttributeName, value: UIColor.orange, range: NSRange(location: (strTitle.characters.count ), length: (strName.characters.count ) + 1))
    self.txtView.attributedText = commentString
    

    希望这段代码对你有所帮助。

    【讨论】:

      猜你喜欢
      • 2021-07-17
      • 2019-02-18
      • 2020-08-07
      • 1970-01-01
      • 2016-06-13
      • 1970-01-01
      • 2021-11-16
      • 2013-02-10
      • 2012-04-13
      相关资源
      最近更新 更多