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

有时候后端传值一个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可以灵活修改字体,字号,颜色等,富文本需求常用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值