最新消息:文章中包含代码时,请遵守代码高亮规范!

iOS UITextView加载有HTML标签的HTML代码【原创】

iOS Alina 4898浏览 0评论

在开发中,我们加载HTML最常用的是UIWebView,其实UITextView也可以加载HTML代码。

- (void)viewDidLoad {
    [super viewDidLoad];
    
    UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 40, kScreenWidth, kScreenHeight - 50)];
    [self.view addSubview:textView];
    
    //HTML代码
   NSString *htmlStr = @"

<img src=\"http://img0.imgtn.bdimg.com/it/u=1368418777,3304551799&fm=21&gp=0.jpg\"

hiuehuirhfiefguihuiefuwifhewufcehsifhoifhiofhwohfwiohfwoicehicehiheifjkhuhuihwefhuiwhfibfiwehfurwhfuiwhfuiwefhuirwhfiw

<img src=\"http://img0.imgtn.bdimg.com/it/u=331456922,2614791273&fm=21&gp=0.jpg\"

hviurhrihvuerhviohvoiwehvewiohiowhviowvhoiheiohihuihguguygigdusichvregtgtgegtgvrtvtrbtrbtrbtrbtrbtbtvrgeggergrbrt<img src=\"http://img3.imgtn.bdimg.com/it/u=3236147722,3184690082&fm=21&gp=0.jpg\"

hiuehuirhfiefguihuiefuwifhewufcehsicehicehiheifjkhuhuihwefhuiwhfibfiwehfurwhfuiwhfuiwefhuirwhfiw

";
    
    //对图片大小进行处理,适应屏幕宽度
    NSString *newString = [htmlStr stringByReplacingOccurrencesOfString:@"<img" withString:[NSString stringWithFormat:@"<img width=\"%f\"",kScreenWidth - 10]];
    
    NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:[newString dataUsingEncoding:NSUnicodeStringEncoding] options:@{ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType } documentAttributes:nil error:nil];
    textView.attributedText = attributedString;
}

注意:在info.plist中配置:

<key>App Transport Security Settings</key>
<dict>
  <key>Allow Arbitrary Loads</key>
  <true/>
</dict>

注:

// 当前屏幕宽度
#define kScreenWidth    [UIScreen mainScreen].bounds.size.width
// 当前屏幕高度
#define kScreenHeight   [UIScreen mainScreen].bounds.size.height

转载时请注明出处及相应链接,本文永久地址:http://blog.it985.com/17376.html


pay_weixin
pay_weixin
微信打赏
pay_weixin
支付宝打赏
感谢您对作者Alina的打赏,我们会更加努力!    如果您想成为作者,请点我

您必须 登录 才能发表评论!