更改了子字符串的颜色,但重置了字体设置

时间:2017-02-07 05:42:11

标签: ios swift swift3 uitextview

How to change color of text stirngs inside UITextView in Swift3

我尝试更改子串的颜色,就像引用上面的URL一样。

enter image description here

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。

1 个答案:

答案 0 :(得分:0)

您可以尝试以下代码:

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

希望此代码可以帮助您。