以编程方式更改UITextView中的某些单词的颜色

时间:2017-01-27 14:32:23

标签: ios swift

所以我有一个带有一些文本的UITextView,我希望每次用户输入时,例如,单词“while”,在写完之后它应该变成紫色。此外,我有另一个UITextView只是为了显示内容,没有启用用户交互,我希望每次视图出现时,所有“while”字也是紫色。我该怎么做呢?你能帮我吗?谢谢!

这是我到目前为止所尝试的内容:

let initialText = textView.text!
let string_to_color = "while"
let range = (initialText as NSString).range(of: string_to_color)
let attribute = NSMutableAttributedString.init(string: initialText)
attribute.addAttribute(NSForegroundColorAttributeName, value: UIColor.purple, range: range)
textView.attributedText = attribute

但它只为第一个单词着色。这是用于禁用用户交互的文本字段。我还没有想出如何为包含用户输入的单词的文本字段执行此操作。

1 个答案:

答案 0 :(得分:3)

您没有正确获得范围,这是在Swift 3.0中使用属性字符串的示例:

// get initial text as a String type (you will get this from your textview)
let initialText = "Swift Attributed String"

// create an attribute for the text color, I chose blue color
let myAttribute = [ NSForegroundColorAttributeName: UIColor.blue ]

// create the attributed string and add the blue color attribute
let myString = NSMutableAttributedString(string: initialText, attributes: myAttribute )

// range starting at location 6 with a lenth of 10: "Attributed"
var myRange = NSRange(location: 6, length: 10) 

// OR get range of specific string in initialText
let newRange = (initialText as NSString).range(of: "Attributed")

// change the range of the word "Attributed" to have red text color
myString.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: newRange)

// create another attribute for highlighting
let anotherAttribute = [ NSBackgroundColorAttributeName: UIColor.yellow ]
// set the range of the "Attributed" part of the string to a yellow highlight
myString.addAttributes(anotherAttribute, range: newRange)

您可以使用此策略执行您需要对字符串执行的任何格式设置。只需确保您获得的范围是正确的。