新需求里要做一个类似微博的@功能,第一次做,笔记一下找到的办法
主要还是用到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;
}