【发布时间】: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