Search code examples
objective-cuitextviewtextcolor

How to change some text colors in multiple colored UITextView


A UITextView has some text with black color and some with red color. I want to change only the black color to white color. I have no idea how to select only the black color and change it to white color.


Solution

  • Use method enumerateAttribute:inRange:options:usingBlock:

    Example Obj-C:

    NSMutableAttributedString *string = [[NSMutableAttributedString alloc]initWithString:@"Test Attributed String"];
    [string addAttribute:NSStrokeColorAttributeName value:[UIColor redColor] range:NSMakeRange(3, string.length-3)];
    [string enumerateAttribute:NSStrokeColorAttributeName inRange:NSMakeRange(0, string.length) options:NSAttributedStringEnumerationReverse usingBlock:^(id  _Nullable value, NSRange range, BOOL * _Nonnull stop) {
        // value is color
    }];