iOS文本@功能
来源:互联网 发布:google seo 编辑:程序博客网 时间:2024/06/05 11:33
新需求里要做一个类似微博的@功能,第一次做,笔记一下找到的办法
主要还是用到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
- iOS文本@功能
- ios富文本功能/文字特性设置
- iOS - iOS系统API创建文本到语言功能
- 文本复制粘贴功能
- Android复制文本功能
- IOS 预览功能(轻松实现对各种文本、图片等查看)
- iOS开发~禁用文本输入框拷贝和粘贴等功能
- 文本显示器-静态文本控件功能一览
- IOS UITextField 文本实例
- ios 富文本编辑器
- ios--文本输入控件
- iOS之富文本
- ios 文本键盘回收
- iOS之富文本
- iOS 文本操作
- ios UITextView 提示文本
- ios之富文本
- IOS文本自适应高度
- 001.Two Sum
- Centos 6系统中svn的搭建
- oracle 11.2 增加节点
- 对于Dubbo框架的一些小分享
- 造成mysql全表扫描的原因
- iOS文本@功能
- QT QML初体验随笔之QQuickView(9)
- hadoop中的filesystem和localfilesystem
- MySQL性能调优my.cnf详解
- win10重新装机后的一点配置
- Netty4框架的初步使用
- JSON中数据对象嵌套
- 怎么根据读到的ADC值,推算实际电压值(二)
- 用dlib和opencv进行不同角度人脸检测及68个关键点提取(Python)