仿新浪微博发布时 @ 及 #某话题# 的效果

项目需要实现如下效果:

 我实现的思路是,监听textView的变化,然后使用正则匹配出 #话题#@对象 所在位置,动态设置文本的颜色,代码如下:

#pragma mark - UITextViewDelegate
- (void)textViewDidChange:(UITextView *)textView
{
    self.placeholderLbl.hidden = textView.hasText;
    
    NSString *language = textView.textInputMode.primaryLanguage;
    if ([language isEqualToString:@"zh-Hans"]) {//中文输入时
        UITextRange *selectedRange = [textView markedTextRange];
        if (!selectedRange) {
            [self textViewSetAttributedText:textView];
        }
    }else{
        [self textViewSetAttributedText:textView];
    }
}

- (void)textViewSetAttributedText:(UITextView *)textView
{
    NSMutableAttributedString *attributeStr = [[NSMutableAttributedString alloc] initWithString:textView.text];
    // @的规则
    NSString *atPattern = @"@[^\\s]+";
    // #话题#的规则
    NSString *topicPattern = @"#[^#]+#";
    // | 匹配多个条件,相当于 或
    NSString *pattern = [NSString stringWithFormat:@"%@|%@", atPattern, topicPattern];
    // 使用正则匹配出 #某话题# 和 @某对象 所在位置
    NSRegularExpression *regularExpr = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
    NSArray *results = [regularExpr matchesInString:textView.text options:0 range:NSMakeRange(0, textView.text.length)];
    // 遍历结果,设置文本颜色
    for (NSTextCheckingResult *result in results) {
        [attributeStr addAttribute:NSForegroundColorAttributeName value:RGBOF(0x7fa1c1) range:result.range];
    }
    textView.attributedText = attributeStr;
}

猜你喜欢

转载自blog.csdn.net/Alexander_Wei/article/details/78020085