Nit*_*oth 31 objective-c uitextfield uitextview nsattributedstring ios
是否可以在UITextView和UITextField中更改单个单词的颜色?
如果我输入了一个带有符号前面的单词(例如:@word),它的颜色可以改变吗?
Ano*_*dya 66
是的,您需要使用NSAttributedString它,找到RunningAppHere.
扫描单词并找到单词的范围并更改其颜色.
编辑:
- (IBAction)colorWord:(id)sender {
NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:self.text.text];
NSArray *words=[self.text.text componentsSeparatedByString:@" "];
for (NSString *word in words) {
if ([word hasPrefix:@"@"]) {
NSRange range=[self.text.text rangeOfString:word];
[string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
}
}
[self.text setAttributedText:string];
}
Run Code Online (Sandbox Code Playgroud)
编辑2:看截图

这是@Anoop Vaidya回答的快速实现,这个函数检测{| myword |}之间的任何单词,用红色着色这些单词并删除特殊字符,希望这可以帮助别人:
func getColoredText(text:String) -> NSMutableAttributedString{
var string:NSMutableAttributedString = NSMutableAttributedString(string: text)
var words:[NSString] = text.componentsSeparatedByString(" ")
for (var word:NSString) in words {
if (word.hasPrefix("{|") && word.hasSuffix("|}")) {
var range:NSRange = (string.string as NSString).rangeOfString(word)
string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
word = word.stringByReplacingOccurrencesOfString("{|", withString: "")
word = word.stringByReplacingOccurrencesOfString("|}", withString: "")
string.replaceCharactersInRange(range, withString: word)
}
}
return string
}
Run Code Online (Sandbox Code Playgroud)
你可以像这样使用它:
self.msgText.attributedText = self.getColoredText("i {|love|} this!")
Run Code Online (Sandbox Code Playgroud)
修改了@fareed对swift 2.0的回答,这是有效的(在游乐场测试):
func getColoredText(text: String) -> NSMutableAttributedString {
let string:NSMutableAttributedString = NSMutableAttributedString(string: text)
let words:[String] = text.componentsSeparatedByString(" ")
var w = ""
for word in words {
if (word.hasPrefix("{|") && word.hasSuffix("|}")) {
let range:NSRange = (string.string as NSString).rangeOfString(word)
string.addAttribute(NSForegroundColorAttributeName, value: UIColor.redColor(), range: range)
w = word.stringByReplacingOccurrencesOfString("{|", withString: "")
w = w.stringByReplacingOccurrencesOfString("|}", withString: "")
string.replaceCharactersInRange(range, withString: w)
}
}
return string
}
getColoredText("i {|love|} this!")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
25923 次 |
| 最近记录: |