iOS文本@功能

新需求里要做一个类似微博的@功能,第一次做,笔记一下找到的办法

主要还是用到NSMutableAttributeString,通过正则表达式查找文本里的符合规则的文本(@开头,空格结尾)

然后会返回该字段的range(位置和长度)

通过该range找到文字然后添加颜色属性,标记出来,再添加点击链接

再使用UITextView的delegate来写点击事件

附上源码

	NSString *normalStr = text;
            // 表情的规则
            NSString *emotionPattern = @"\\[[0-9a-zA-Z\\u4e00-\\u9fa5]+\\]";
            
            // @的规则
            NSString *atPattern = @"@[0-9a-zA-Z\\u4e00-\\u9fa5]+";
            
            // #话题#的规则
            NSString *topicPattern = @"#[0-9a-zA-Z\\u4e00-\\u9fa5]+#";
            
            // url链接的规则
            NSString *urlPattern = @"\\b(([\\w-]+://?|www[.])[^\\s()<>]+(?:\\([\\w\\d]+\\)|([^[:punct:]\\s]|/)))";
            
            // | 匹配多个条件,相当于or\或
            NSString *pattern = [NSString stringWithFormat:@"%@", atPattern];
            // 使用系统的正则类来遍历
            NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:pattern options:0 error:nil];
            // 2.测试字符串
            NSArray *results = [regex matchesInString:normalStr options:0 range:NSMakeRange(0, normalStr.length)];
            
            NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:normalStr];
            // 3.遍历结果
            for (NSTextCheckingResult *result in results) {
                [attStr addAttribute:NSForegroundColorAttributeName value:RGBACOLOR(35,173,245, 1) range:NSMakeRange(result.range.location, result.range.length)];
                [attStr addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:16] range:NSMakeRange(result.range.location, result.range.length)];
                //添加链接的方式
                [attStr addAttribute:NSLinkAttributeName
                               value:[NSString stringWithFormat:@"username://%@",[normalStr substringWithRange:result.range]]
                               range:result.range];
                //    设置点击时的样式
                NSDictionary *linkAttributes =@{NSForegroundColorAttributeName: RGBCOLOR(53, 180, 246),NSUnderlineColorAttributeName: LineColor,NSUnderlineStyleAttributeName:@(NSUnderlinePatternSolid)};
                //    添加链接文字
                _repostView.linkTextAttributes = linkAttributes;
            }
            
            [_repostView.textStorage setAttributedString:attStr];
代理方法:

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    
    //需要处理的代码,例如通过range获取名字,然后查找
    return YES;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值