Search code examples
iosobjective-ctextviewnsmutableattributedstring

How to find mutiple words in textview for changing color of it


I am working on project in which I took a texview and its delegate method below

-(void)textViewDidChange:(UITextView *)textView
{
    NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc]initWithString:textView.text];
    NSUInteger characterCount = [attstr length];
    NSString *str = @"football";
    NSUInteger searchlength = [str length];
    NSRange range1 = NSMakeRange(0, attstr.length);
    while (range1.location != NSNotFound) {
        range1 =[attstr.string rangeOfString:str options:0 range:range1];
        if (range1.location !=NSNotFound) {
            [attstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range1.location, searchlength)];
            [attstr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0]  range:range1];
            range1 = NSMakeRange(range1.location + range1.length, characterCount -(range1.location + range1.length));
            textView.attributedText = attstr;
        }
    }
}

Now in that method, I am finding keyword "football" and change its color to redcolor. Here I am searching for a single string, So what should I do for checking for multiple strings like array

My problem is How can I find multiple strings at a time into text of textview.

Please help me with it
Thank you


Solution

  • I achieved this thing like this

    -(void)textViewDidChange:(UITextView *)textView
    {
        NSMutableAttributedString *attstr = [[NSMutableAttributedString alloc]initWithString:textView.text];
        NSUInteger characterCount = [attstr length];
        NSArray *arr = [[NSArray alloc]initWithObjects:@"football",@"player",nil];
    
        for (int i=0; i<arr.count; i++) {
    
        NSUInteger searchlength = [[NSString stringWithFormat:@"%@",[arr objectAtIndex:i]] length];
        NSRange range1 = NSMakeRange(0, attstr.length);
    
        while (range1.location != NSNotFound) {
            range1 =[attstr.string rangeOfString:[NSString stringWithFormat:@"%@",[arr objectAtIndex:i]] options:0 range:range1];
            if (range1.location !=NSNotFound) {
                [attstr addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(range1.location, searchlength)];
                [attstr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:20.0]  range:range1];
                range1 = NSMakeRange(range1.location + range1.length, characterCount -(range1.location + range1.length));
                textView.attributedText = attstr;
            }
        }
    }