项目需要实现如下效果:
这边我实现的思路是,监听textView的变化,然后用enumerateSubstringsInRange扫描所有字符,动态设置文本的颜色,见下:
- (void)textViewDidChange:(UITextView *)textView
{
NSString *str = textView.text;
__block NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:str];
[attributeStr addAttribute:NSForegroundColorAttributeName value:color_000000 range:NSMakeRange(0,str.length)];
__block NSInteger startIndex = -1,endIndex = -1;
[str enumerateSubstringsInRange:NSMakeRange(0, str.length) options:NSStringEnumerationByComposedCharacterSequences|NSStringEnumerationLocalized usingBlock:^(NSString * _Nullable substring, NSRange substringRange, NSRange enclosingRange, BOOL * _Nonnull stop)
{
if (startIndex == -1 && ([substring isEqualToString:@"#"] || [substring isEqualToString:@"#"]))
{
startIndex = substringRange.location;
}
else if (startIndex != -1)
{
endIndex = substringRange.location;
}
if (startIndex != -1 && endIndex != -1 && ([substring isEqualToString:@"#"] || [substring isEqualToString:@"#"]))
{
[attributeStr addAttribute:NSForegroundColorAttributeName value:theme_skin_color range:(NSRange){startIndex,(endIndex - startIndex) + 1}];
startIndex = -1;
endIndex = -1;
}
}];
textView.attributedText = attributeStr;
}