如何加载html格式的文本

来源:互联网 发布:网络说唱歌手皇甫 编辑:程序博客网 时间:2024/05/21 11:14

1.使用一般的控件(比如:UILabel、UITextView)加载HTML

// 使用NSMutableAttributedString来转换HTML文本NSString *htmlStr = @"<p>易微行用户\r</p><p>demo测试用户协议\r</p><p>公司地址\r</p><p>联系电话\r</p><p>电子邮件</p>";NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithData:[htmlStr dataUsingEncoding:NSUnicodeStringEncoding] options:@{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType} documentAttributes:nil error:nil];[attStr addAttributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16]} range:NSMakeRange(0, attStr.length)];UITextView *textView = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height-self.navigationController.navigationBar.frame.origin.y-self.navigationController.navigationBar.frame.size.height)];textView.showsVerticalScrollIndicator = NO;textView.editable = NO;textView.attributedText = attStr;[self.view addSubview:textView];

2.使用UIWebView加载HTML

NSString *htmlStr = @"<p>易微行用户\r</p><p>demo测试用户协议\r</p><p>公司地址\r</p><p>联系电话\r</p><p>电子邮件</p>";UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64)];webView.userInteractionEnabled = NO;// 这个方法需要将httml文件读取为字符串,其中baseURL是我们自己设置的一个路径,用于寻找html文件中引用的图片等素材[webView loadHTMLString:htmlStr baseURL:nil];[self.view addSubview:webView];

结果:

这里写图片描述

0 0