ios 是否可以更改 UITextView 和 UITextField 中单个单词的颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14231879/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is it possible to change color of single word in UITextView and UITextField
提问by Nithin M Keloth
Is it possible to change color of single word in UITextView and UITextField ?
是否可以更改 UITextView 和 UITextField 中单个单词的颜色?
If i have typed a word with a symbol infront (eg: @word) , can it's color be changed ?
如果我输入了一个前面带有符号的单词(例如:@word),它的颜色可以改变吗?
回答by Anoop Vaidya
Yes you need to use NSAttributedString
for that, find the RunningAppHere.
是的,您需要为此使用NSAttributedString
,找到RunningAppHere。
Scan through the word and find the range of your word and change its color.
扫描单词并找到单词的范围并更改其颜色。
EDIT:
编辑:
- (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];
}
EDIT 2 : see the screenshot
编辑2:看截图
回答by Fareed Alnamrouti
this is a swift implementation from @Anoop Vaidyaanswer,this function detect any word between {|myword|} , color these words in red and remove the special characters, hope this may help someone else:
这是@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
}
you can use it like this:
你可以这样使用它:
self.msgText.attributedText = self.getColoredText("i {|love|} this!")
回答by chapani
Modified @fareed's answer for swift 2.0 and this is working (tested in a playground):
修改了@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!")
回答by Eugene Gordin
@fareed namroutiimplementation rewritten in Swift 3
@fareed namrouti实现在 Swift 3 中重写
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
}
回答by skittle
-(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];
}
回答by AlphaCodaSeven
To expound on Jamal Kharrat's answer, and to rewrite it into SWIFT, here is how to do it in a UITextView:
为了阐述 Jamal Kharrat 的回答,并将其重写为 SWIFT,这里是如何在 UITextView 中执行此操作:
- Set your UITextView to "Attributed" in the storyboard
- Right-click & drag to ViewController icon at the top of the view (XC 6), and set the delegate
- Create an IBOutlet for your UITextView (we'll call it "textView")
- Make your class conform to UITextViewDelegate
- 在情节提要中将您的 UITextView 设置为“归因”
- 右键单击并拖动到视图顶部的 ViewController 图标(XC 6),并设置委托
- 为您的 UITextView 创建一个 IBOutlet(我们将其称为“textView”)
- 让你的类符合 UITextViewDelegate
Here is Jamal's function written in SWIFT:
这是 Jamal 用 SWIFT 编写的函数:
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
}
Now, you'll need to call this function. To do this every time the user types a character, you can use:
现在,您需要调用此函数。要在每次用户键入字符时执行此操作,您可以使用:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
self.colorHastag()
return true
}
You'll notice that I changed the color to blue. You can set it to any color. Also, you can strip out the :Type for every variable. You'll also want to set becomeFirstResponder() and also handle resignFirstResponder() for a good user experience. You could also throw in some error handling. This will only convert hashtags to blue. You will need to modify or add a regEx to handle the @.
您会注意到我将颜色更改为蓝色。您可以将其设置为任何颜色。此外,您可以去掉每个变量的 :Type 。您还需要设置 becomeFirstResponder() 并处理 resignFirstResponder() 以获得良好的用户体验。您还可以进行一些错误处理。这只会将主题标签转换为蓝色。您将需要修改或添加一个正则表达式来处理@。
回答by Catalin
The solution is this:
解决办法是这样的:
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];
回答by Brandon A
Yes it is possible. However I have found it can be a headache trying to use NSMutableAttributesString
with a Swift Range
. The code below will get you around having to use the Range
class and return you an attributed string with the words highlighted a different color.
对的,这是可能的。但是我发现尝试NSMutableAttributesString
与 Swift一起使用可能会令人头疼Range
。下面的代码将使您不必使用Range
该类并返回一个属性字符串,其中的单词以不同的颜色突出显示。
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
}
}
Usage:
用法:
// 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
回答by Andrei Boleac
After setting an attributedtext you can set typingAttributes of UITextView
with the values you want for you input field.
设置属性文本后UITextView
,您可以使用输入字段所需的值设置typingAttributes 。
NSDictionary *attribs = @{
NSForegroundColorAttributeName:[UIColor colorWithHex:kUsernameColor],
NSFontAttributeName:[UIFont robotoRegularWithSize:40]
};
self.textView.typingAttributes = attribs;