Is it possible to change color of single word in U

2019-01-05 03:00发布

Is it possible to change color of single word in UITextView and UITextField ?

If i have typed a word with a symbol infront (eg: @word) , can it's color be changed ?

9条回答
叼着烟拽天下
2楼-- · 2019-01-05 03:37

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.

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
查看更多
地球回转人心会变
3楼-- · 2019-01-05 03:42
-(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];
}
查看更多
甜甜的少女心
4楼-- · 2019-01-05 03:48

this is a swift implementation from @Anoop Vaidya answer,this function detect any word between {|myword|} , color these words in red and remove the special characters, hope this may help someone else:

 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!")
查看更多
5楼-- · 2019-01-05 03:51

Yes you need to use NSAttributedString for that, find the 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 enter image description here

查看更多
手持菜刀,她持情操
6楼-- · 2019-01-05 03:53

After setting an attributedtext you can set typingAttributes of UITextView with the values you want for you input field.

NSDictionary *attribs = @{
    NSForegroundColorAttributeName:[UIColor colorWithHex:kUsernameColor],
    NSFontAttributeName:[UIFont robotoRegularWithSize:40]
};
self.textView.typingAttributes = attribs;
查看更多
虎瘦雄心在
7楼-- · 2019-01-05 03:55

Modified @fareed's answer for swift 2.0 and this is working (tested in a playground):

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!")
查看更多
登录 后发表回答