How to change color of text stirngs inside UITextView in Swift3
我尝试像这样引用上面的网址来更改子字符串的颜色。
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。
最佳答案
您可以尝试以下代码:
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
希望这段代码对您有帮助。
关于ios - 更改了子字符串的颜色,但字体设置已重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42082558/