是否可以更改UITextView和UITextField中单个单词的颜色

是否有可能改变UITextView和UITextField单个单词的颜色?

如果我用一个符号infront(例如:@word)键入一个单词,它的颜色可以改变吗?

是的,你需要使用NSAttributedString ,findRunningAppHere 。

扫描单词并找出单词的范围并更改其颜色。

编辑:

 - (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]; } 

编辑2:看截图 在这里输入图像描述

修改@ fareed的答案为迅速2.0,这是工作(在操场上testing):

 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!") 

这是一个从@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 } 

你可以像这样使用它:

 self.msgText.attributedText = self.getColoredText("i {|love|} this!") 

在Swift 3中重写了实现的namrouti实现

 func getColoredText(text: String) -> NSMutableAttributedString { let string:NSMutableAttributedString = NSMutableAttributedString(string: text) let words:[String] = text.components(separatedBy:" ") var w = "" for word in words { if (word.hasPrefix("{|") && word.hasSuffix("|}")) { let range:NSRange = (string.string as NSString).range(of: word) string.addAttribute(NSForegroundColorAttributeName, value: UIColor.red, range: range) w = word.replacingOccurrences(of: "{|", with: "") w = w.replacingOccurrences(of:"|}", with: "") string.replaceCharacters(in: range, with: w) } } return string } 
 -(void)colorHashtag { NSMutableAttributedString * string = [[NSMutableAttributedString alloc]initWithString:textView.text]; NSString *str = textView.text; NSError *error = nil; //I Use regex to detect the pattern I want to change color NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+)" options:0 error:&error]; NSArray *matches = [regex matchesInString:textView.text options:0 range:NSMakeRange(0, textView.text.length)]; for (NSTextCheckingResult *match in matches) { NSRange wordRange = [match rangeAtIndex:0]; [string addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:wordRange]; } [textView setAttributedText:string]; } 

为了阐述Jamal Kharrat的回答,并将其改写成SWIFT,下面是如何在UITextView中完成的:

  1. 在故事板中将你的UITextView设置为“Attributed”
  2. 右键单击并拖动到视图(XC 6)顶部的ViewController图标,然后设置委托
  3. 为您的UITextView创build一个IBOutlet(我们将其称为“textView”)
  4. 使你的类符合UITextViewDelegate

这里是用SWIFT编写的Jamal函数:

 func colorHastag(){ var string:NSMutableAttributedString = NSMutableAttributedString(string: textView.text) var str:NSString = textView.text var error:NSError? var match:NSTextCheckingResult? var regEx:NSRegularExpression = NSRegularExpression(pattern: "#(\\w+)", options: nil, error: &error)! var matches:NSArray = regEx.matchesInString(textView.text, options: nil, range: NSMakeRange(0, countElements(textView.text))) for (match) in matches { var wordRange:NSRange = match.rangeAtIndex(0) string.addAttribute(NSForegroundColorAttributeName, value: UIColor.blueColor(), range: wordRange) } textView.attributedText = string } 

现在,你需要调用这个函数。 每当用户键入一个字符时,都可以使用:

 func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool { self.colorHastag() return true } 

你会注意到我把颜色改成了蓝色。 您可以将其设置为任何颜色。 此外,你可以去掉:为每个variables键入。 您还需要设置becomeFirstResponder()并处理resignFirstResponder()以获得良好的用户体验。 你也可以抛出一些error handling。 这只会将标签转换为蓝色。 您将需要修改或添加regEx来处理@。

解决方法是这样的:

 NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] init]; NSArray *words=[txtDescription.text componentsSeparatedByString:@" "]; for (NSString *word in words) { if ([word hasPrefix:@"@"] || [word hasPrefix:@"#"]) { [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ", word] attributes:@{NSFontAttributeName: [UIFont fontWithName:FONT_LIGHT size:15], NSForegroundColorAttributeName: [ImageToolbox colorWithHexString:@"f64d5a"]}]]; } else // normal text { [attributedString appendAttributedString:[[NSAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ", word] attributes:@{NSFontAttributeName: [UIFont fontWithName:FONT_LIGHT size:15], NSForegroundColorAttributeName: [ImageToolbox colorWithHexString:@"3C2023"]}]]; } } if([[attributedString string] hasSuffix:@" "]) // loose the last space { NSRange lastCharRange; lastCharRange.location=0; lastCharRange.length=[attributedString string].length-1; attributedString=[[NSMutableAttributedString alloc] initWithAttributedString:[attributedString attributedSubstringFromRange:lastCharRange]]; } [txtDescription setAttributedText:attributedString]; 

是的,这是可能的。 然而,我发现它可能是一个头痛的尝试使用Swift Range NSMutableAttributesString 。 下面的代码会让你不得不使用Range类,并返回一个属性string,其中单词突出显示不同的颜色。

 extension String { func getRanges(of string: String) -> [NSRange] { var ranges:[NSRange] = [] if contains(string) { let words = self.components(separatedBy: " ") var position:Int = 0 for word in words { if word.lowercased() == string.lowercased() { let startIndex = position let endIndex = word.characters.count let range = NSMakeRange(startIndex, endIndex) ranges.append(range) } position += (word.characters.count + 1) // +1 for space } } return ranges } func highlight(_ words: [String], this color: UIColor) -> NSMutableAttributedString { let attributedString = NSMutableAttributedString(string: self) for word in words { let ranges = getRanges(of: word) for range in ranges { attributedString.addAttributes([NSForegroundColorAttributeName: color], range: range) } } return attributedString } } 

用法:

 // The strings you're interested in let string = "The dog ran after the cat" let words = ["the", "ran"] // Highlight words and get back attributed string let attributedString = string.highlight(words, this: .yellow) // Set attributed string textView.attributedText = attributedString