iOS TextView与HTML结合以及设置超链接

有时候后端传值一个HTML的字符串,要前台展示,实现这一方法用UILable和UITextView均可以实现,但是要实现超链接的点击,我研究出用UITextView更方便,

实现效果如下:

iOS TextView与HTML结合以及设置超链接_第1张图片

代码如下:

 添加代理 

//html字符串
NSString * htmlStr = @"Enter \"My Coupon\" page to.3. Go to your “My Coupon” page to view your Coupon!
4. GearBest reserves the right to amend this activity. For any queries, please contact our Support Staff. (https://www.baidu.com)"; //初始化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可以灵活修改字体,字号,颜色等,富文本需求常用

你可能感兴趣的:(oc基础)