UITextView使用

- (UITextView*)contentTextView {if (!_contentTextView) {_contentTextView = [[UITextView alloc] init];_contentTextView.textAlignment = NSTextAlignmentLeft;_contentTextView.delegate = self;// 必须禁止输入,否则点击将弹出输入键盘_contentTextView.editable = NO;_contentTextView.scrollEnabled = NO;_contentTextView.backgroundColor = [UIColor clearColor];_contentTextView.showsVerticalScrollIndicator = NO;_contentTextView.showsHorizontalScrollIndicator = NO;_contentTextView.contentInset = UIEdgeInsetsZero;_contentTextView.scrollIndicatorInsets = UIEdgeInsetsZero;_contentTextView.contentOffset = CGPointZero;_contentTextView.textContainerInset = UIEdgeInsetsZero;_contentTextView.textContainer.lineFragmentPadding = 0;}return _contentTextView;
}

textView赋值:
当文本内容里有链接需要点击跳转时:

NSString*string =@"自定义"];NSMutableAttributedString* mutAttributedString = [[NSMutableAttributedString alloc]initWithString:stringattributes:@{NSFontAttributeName : IS_FONT(15),NSForegroundColorAttributeName : IS_COLOR_HEX(@"#202020")}];NSString* channelString = @"去频道";[mutAttributedStringappendAttributedString:[[NSAttributedString alloc]initWithString:channelStringattributes:@{NSFontAttributeName : IS_FONT(15)}]];NSRange channelRange =[mutAttributedString.string rangeOfString:channelString];NSString* channelUrlString = [NSStringstringWithFormat:@"channel://%@", self.experienceModel.idString];[mutAttributedString addAttribute:NSLinkAttributeNamevalue:channelUrlStringrange:channelRange];// 解析文本内链接[self analyseUrlWithContentString:mutAttributedString];contentTextView.attributedText =mutAttributedString;

textView代理方法

#pragma mark--- protocolTextView-UITextViewdelegate
- (BOOL)textView:(UITextView*)textViewshouldInteractWithURL:(NSURL*)URLinRange:(NSRange)characterRange {if ([[URL scheme] isEqualToString:@"channel"]) {NSString* channelIdString =[NSString stringWithFormat:@"%@", URL.absoluteString];channelIdString =[channelIdString stringByReplacingOccurrencesOfString:@"channel://"withString:@""];// 物品赠送反馈系统消息类型----去频道// [self pushTalkViewWithChannelShowId:channelIdString];} else {// 文本内链接识别跳转// 解码NSString* requestString =[URL.absoluteString stringByRemovingPercentEncoding];if (requestString && requestString.length > 0) {// [self pushTalkViewWithUrlString:[NSString//                                     stringWithFormat:@"%@",//        URL.absoluteString]];}}return NO;
}

解析UITextView字符串里的链接并改成图片文本

#pragma mark-- 递归解析纯文本的链接
- (void)analyseTextViewUrlWithContentString:(NSMutableAttributedString*)attributedStr {NSError* error = nil;NSString* regulaStr =@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/"@"[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/"@"=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/"@"[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";NSRegularExpression* regex = [NSRegularExpressionregularExpressionWithPattern:regulaStroptions:NSRegularExpressionCaseInsensitiveerror:&error];NSArray* arrayOfAllMatches =[regex matchesInString:attributedStr.stringoptions:0range:NSMakeRange(0, attributedStr.string.length)];// 替换链接为汉字-"网页链接"NSMutableAttributedString* webLinkAttributedString =[[NSMutableAttributedString alloc]initWithString:@" 网页链接"attributes:@{NSFontAttributeName : IS_FONT(15),NSForegroundColorAttributeName : IS_COLOR_HEX(@"#3A83DC")}];UIImage* image = [UIImage imageNamed:@"QHWebLinkImage"];// UILabel 显示的图片富文本NSTextAttachment* textAttachment = [[NSTextAttachment alloc] init];textAttachment.image = image;CGFloat textPaddingTop =(IS_FONT(15).lineHeight - IS_FONT(15).pointSize) * 0.5;textAttachment.bounds =CGRectMake(0, -textPaddingTop, image.size.width, image.size.height);NSAttributedString* imageStr =[NSAttributedString attributedStringWithAttachment:textAttachment];[webLinkAttributedString insertAttributedString:imageStr atIndex:0];// 我们得到一个数组,这个数组中NSTextCheckingResult元素中包含我们要找的URL的range,// 当然可能找到多个URL,找到相应的URL的位置,用YYlabel的高亮点击事件处理跳转网页if (arrayOfAllMatches && arrayOfAllMatches.count > 0) {NSTextCheckingResult* match = arrayOfAllMatches[0];NSString* urlString = [attributedStr.string substringWithRange:match.range];[attributedStr replaceCharactersInRange:match.rangewithAttributedString:webLinkAttributedString];NSRange webLinkRange =NSMakeRange(match.range.location, webLinkAttributedString.length);// 对链接进行编码NSString* urlEncodeString =[urlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];[attributedStr addAttribute:NSLinkAttributeNamevalue:urlEncodeStringrange:webLinkRange];// 检测剩下的字符串中链接NSArray* leftMatches =[regex matchesInString:attributedStr.stringoptions:0range:NSMakeRange(0, attributedStr.string.length)];if (leftMatches.count > 0) {[self analyseUrlWithContentString:attributedStr];}}
}

赋值YYlabel或UITextView

-(void)updateContentLabel{NSString*string =@"自定义"];
NSString* channelString = @"去频道";
[mutAttributedString appendAttributedString:[[NSAttributedString alloc] initWithString:string attributes:@{  NSFontAttributeName : IS_FONT(15)}]];
NSRange channelRange =[mutAttributedString.string rangeOfString:channelString];
weak_IS(weakSelf);
[mutAttributedStringyy_setTextHighlightRange:channelRangecolor:[UIColorcolorWithHexString:@"#3A83DC"]backgroundColor:[UIColor colorWithWhite:1.0 alpha:0.6]         tapAction:^(UIView* containerView,NSAttributedString* text, NSRange range, CGRect rect) {[weakSelf pushTalkViewWithChannelShowId:weakSelf.experienceModel.idString];}];// 解析文本内链接
//  UITextView解析[self analyseTextViewUrlWithContentString:mutAttributedString];// 或者YYlabel解析[self analyseYYlabelWithContentString:mutAttributedString];_contentLabel.attributedText =mutAttributedString;}

YYlabel使用

识别富文本内容里边的链接并跳转:

- (YYLabel*)contentLabel {if (!_contentLabel) {_contentLabel = [[YYLabel alloc] init];_contentLabel.layer.cornerRadius=ChatViewGroupAndFriendMessageIconWH / 2;_contentLabel.layer.shouldRasterize = YES;_contentLabel.numberOfLines = 0;_contentLabel.font = [UIFont systemFontOfSize:15];_contentLabel.layer.rasterizationScale = [UIScreen mainScreen].scale;_contentLabel.backgroundColor = [UIColor clearColor];}return _contentLabel;
}

解析yylabel的富文本

- (void)analyseYYlabelWithContentString:(NSMutableAttributedString*)attributedStr {NSError* error = nil;NSString* regulaStr =@"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/"@"[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/"@"=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/"@"[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";NSRegularExpression* regex = [NSRegularExpressionregularExpressionWithPattern:regulaStroptions:NSRegularExpressionCaseInsensitiveerror:&error];NSArray* arrayOfAllMatches =[regex matchesInString:attributedStr.stringoptions:0range:NSMakeRange(0, attributedStr.string.length)];// 替换链接为汉字-"网页链接"NSMutableAttributedString* webLinkAttributedString =[[NSMutableAttributedString alloc]initWithString:@" 网页链接"attributes:@{NSFontAttributeName : IS_FONT(15),NSForegroundColorAttributeName : IS_COLOR_HEX(@"#3A83DC")}];UIImage* image = [UIImage imageNamed:@"QHWebLinkImage"];NSAttributedString* imageStr = [NSAttributedStringyy_attachmentStringWithContent:imagecontentMode:UIViewContentModeScaleAspectFillattachmentSize:CGSizeMake(image.size.width,image.size.height)alignToFont:IS_FONT(13)alignment:YYTextVerticalAlignmentCenter];[webLinkAttributedString insertAttributedString:imageStr atIndex:0];// 我们得到一个数组,这个数组中NSTextCheckingResult元素中包含我们要找的URL的range,weak_IS(weakSelf);// 当然可能找到多个URL,找到相应的URL的位置,用YYlabel的高亮点击事件处理跳转网页for (NSTextCheckingResult* match in arrayOfAllMatches) {NSString* urlString = [attributedStr.string substringWithRange:match.range];[attributedStr replaceCharactersInRange:match.rangewithAttributedString:webLinkAttributedString];NSRange webLinkRange =NSMakeRange(match.range.location, webLinkAttributedString.length);[attributedStryy_setTextHighlightRange:webLinkRangecolor:[UIColor colorWithHexString:@"#3A83DC"]backgroundColor:[UIColor colorWithWhite:1.0 alpha:0.6]tapAction:^(UIView* containerView,NSAttributedString* text, NSRange range,CGRect rect) {[weakSelf pushTalkViewWithUrlString:urlString];}];// 检测剩下的字符串中链接NSArray* leftMatches =[regex matchesInString:attributedStr.stringoptions:0range:NSMakeRange(0, attributedStr.string.length)];if (leftMatches.count > 0) {[self analyseUrlWithContentString:attributedStr];break;}}
}

总结

YYlabel 赋值富文本后计算文本高度有时会计算不准确,导致出现文字显示不全的问题。
UITextView使用更加便捷,功能性更强,也可长按复制等操作。

UITextView使用与YYlabel使用比较相关推荐

  1. iOS UILabel UITextView自适应文本,或文本大小自适应

    //UILabel自适应文本的高度 UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(0, 100, 300, 100)];label ...

  2. iOS UITextView 随键盘弹出界面上移

    - (void)textViewDidBeginEditing:(UITextView *)textView { CGRect frame = textView.frame; int offSet = ...

  3. Swift - 多行文本输入框(UITextView)的用法

    1,多行文本控件的创建 1 2 3 4 var textview=UITextView(frame:CGRectMake(10,100,200,100)) textview.layer.borderW ...

  4. UITextView 取消键盘方法

    首先UITextView 要实现delegate UITextViewDelegate 然后在.m文件里实现该协议: - (void)textViewDidBeginEditing:(UITextVi ...

  5. IOS学习笔记(四)之UITextField和UITextView控件学习

    IOS学习笔记(四)之UITextField和UITextView控件学习(博客地址:http://blog.csdn.net/developer_jiangqq) Author:hmjiangqq ...

  6. UITextView中的占位符

    我的应用程序使用UITextView . 现在,我希望UITextView具有类似于可以为UITextField设置的占位符. 这个怎么做? #1楼 简单的方法,只需使用以下UITextViewDel ...

  7. UITextView左边距为0

    UITextView左边距为0 [TextView.textContainer setLineFragmentPadding:.0]; [TextView.layoutManager setAllow ...

  8. 【iOS 开发】基本 UI 控件详解 (UIButton | UITextField | UITextView | UISwitch)

    博客地址 : http://blog.csdn.net/shulianghan/article/details/50051499 ; 一. UI 控件简介 1. UI 控件分类 UI 控件分类 : 活 ...

  9. UITextField与UITextView的区别

    2019独角兽企业重金招聘Python工程师标准>>> UITextField继承UIControl 1.文字永远是一行,不能显示多行文字 2.有placehoder属性设置占位文字 ...

  10. iOS开发 - UITextView输入时高度自适应

    2019独角兽企业重金招聘Python工程师标准>>> // 设置边距 依次为:上,左,下, 右 textView.textContainerInset = UIEdgeInsets ...

最新文章

  1. (0108)iOS开发之Xcode11: 删除默认Main.storyBoard、自定义根控制器
  2. Android5.1设备无法识别exFAT文件系统的64G TF卡问题
  3. 戳破“砖家”假面:唯快不破的时代,为什么这件事一定要慢慢做?
  4. 7-5 计算分段函数[3] (10 分)
  5. 如何将Java Web项目部署到服务器上
  6. 用Markdown记笔记后转换成html
  7. docx文档文字怎么加边框_Word技巧:怎么给文本加方框
  8. 如何在OpenStack-Ansible上集成Tungsten Fabric
  9. 【Lintcode】1896. Pick Carrots
  10. 牛牛的旅游纪念品(背包DP)
  11. 【记录】我的一个Centos开机自启动脚本的制作
  12. 正则表达式元字符查询
  13. 再一次感受爱的力量!
  14. 史上最好最全最牛的安全驾驶经验(不看必后悔)
  15. ime-mode 不支持Chrome | 输入框限制输入语言
  16. ArcGis实战:土地利用变化矩阵与土地利用变化图制作
  17. 证书吊销列表(CRL)简单介绍与相关openssl C api功能测试
  18. 艾默生流量计类型流量计的应用特点
  19. 2022-11-14:rust语言,请使用过程宏给结构体AAA生成结构体AAABuilder和创建AAABuilder实例的方法。 宏使用如下: #[derive(Builder)] pub stru
  20. iOS 判断手机型号(已更新至iPhone 14 Pro Max)

热门文章

  1. linux之U盘读写速度测试
  2. 公众号运营工具有哪些?
  3. 逻辑回归算法梳理(从理论到示例)
  4. 店铺淘口令怎么生成, 怎么生成店铺淘口令
  5. 数据库读写分离下的数据同步解决方案
  6. c++病毒代码(附源码)
  7. MATLAB Radon检测图像,初学radon变换 检测直线 matlab程序实现
  8. 浩辰ICAD电气软件IDq2003i.rar
  9. C++泛型编程——迭代器
  10. QNX系统和凝思系统分别系统时间设置RTC时间方法