有时候后端传值一个HTML的字符串,要前台展示,实现这一方法用UILable和UITextView均可以实现,但是要实现超链接的点击,我研究出用UITextView更方便,
实现效果如下:
代码如下:
添加代理 <UITextViewDelegate>
//html字符串
NSString * htmlStr = @"Enter <a href=\"https://app-gearbest.com.trunk.s1.egomsl.com/my-coupon.html\" target=\"_blank\"><b>\"My Coupon\"</b></a> page to.3. Go to your “My Coupon” page to view your Coupon!<br>4. GearBest reserves the right to amend this activity. For any queries, please contact our Support Staff. (<a href=\"https://www.baidu.com\" target=\"_blank\">https://www.baidu.com</a>)";
//初始化textView控件
_contentView = [[UITextView alloc] init];
_contentView.textColor = H_BLACKTEXTCOLOR;
_contentView.delegate = self;
[_contentView setSelectable: YES];
[_contentView setEditable:NO];
_contentView.dataDetectorTypes = UIDataDetectorTypeLink;
//html转化成字符串
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
_contentView.attributedText = attributedString;
_contentView.font = H_FONTTITLE;
[self addSubview:_contentView];
//textView的代理方法
- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange
{
//可在此做业务需求的跳转
return YES;//返回YES,直接跳转Safari
}
//根据字符串动态获取textView的高度
CGSize sizeToFit = [_contentView sizeThatFits:CGSizeMake(contentSize.width, MAXFLOAT)];
self.contentView.frame = CGRectMake(contentInsets.left, 0,contentSize.width, sizeToFit.height);
ps:传值html可以灵活修改字体,字号,颜色等,富文本需求常用