search
HomeWeb Front-endHTML TutorialUITextView和UILabel加载HTML_html/css_WEB-ITnose

前言

最近有不少朋友们、群友们经常问到UITextView如何加载HTML?UILabel能加载HTML吗?或者问后台接口返回来的是HTML格式的数据,我该怎么显示呢?怎么处理呢?

在这里,笔者针对这些朋友、群友们的反馈,尝试写了个小demo,希望能够帮助到大家吧!

Demo效果截图

这demo中是放在cell里面加载的,并且教大家如何自动计算行高。不过UITextView计算行高是有误差的,因为笔者没有使用更高级的处理,直接使用了sizeThatFits这个API来计算高度。而UITextView天生就不一样,它有上、下、左、右的间隔的,因此计算出来是有一点小偏差的。

本篇文章只讲如何加载,不讲如何精确计算!

使用到NSAttributedString

通过它就可以设置加载HTML。但是,要让UILabel可以加载HTML,要求在iOS7之后才可以使用:

 - (nullableinstancetype)initWithData:(NSData *)dataoptions:(NSDictionary*)optionsdocumentAttributes:(NSDictionary* __nullable* __nullable)dicterror:(NSError **)errorNS_AVAILABLE(10_0, 7_0);

其中,options中的指定key为:

 UIKIT_EXTERN NSString * const NSDocumentTypeDocumentAttribute NS_AVAILABLE(10_0, 7_0);

时,它可以选择的值有:

 UIKIT_EXTERN NSString * const NSPlainTextDocumentType NS_AVAILABLE(10_0, 7_0);UIKIT_EXTERN NSString * const NSRTFTextDocumentType NS_AVAILABLE(10_0, 7_0);UIKIT_EXTERN NSString * const NSRTFDTextDocumentType NS_AVAILABLE(10_0, 7_0);UIKIT_EXTERN NSString * const NSHTMLTextDocumentType NS_AVAILABLE(10_0, 7_0);

其中,NSHTMLTextDocumentType就是设置要加载HTML了。

UILabel加载HTML

UILabel在iOS6.0后提供了一个属性用于设置各种呈现的样式:

 @property(null_resettable,copy) NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0);

虽然attributedText属性是iOS6就可以使用,但是对于加载HTML,要求是在iOS7以上才能使用:

 // ios 7.0以后才能使用NSData *data = [model.htmldataUsingEncoding:NSUnicodeStringEncoding];NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};NSAttributedString *html = [[NSAttributedString alloc]initWithData:data                                                            
 options:options                                                 
 documentAttributes:nil                                                              error:nil];self.htmlLabel.attributedText = html;

UITextView加载HTML

UITextView也提供了相关设置文本样式的属性:

 @property(null_resettable,copy) NSAttributedString *attributedText NS_AVAILABLE_IOS(6_0);

与UILabel类似,虽然attributedText属性是iOS6就可以使用,但是对于加载HTML,要求是在iOS7以上才能使用:

 // ios 7.0以后才能使用NSData *data = [model.htmldataUsingEncoding:NSUnicodeStringEncoding];NSDictionary *options = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType};NSAttributedString *html = [[NSAttributedString alloc]initWithData:data                                                            
 options:options                                                 
 documentAttributes:nil                                                              
 error:nil];self.textView.attributedText = html; // 加载HTML后,还要设置行高约束,否则高度就是0CGFloat screenWidth = [UIScreen mainScreen].bounds.size.width;[self.textViewmas_updateConstraints:^(MASConstraintMaker *make) {  make.height.mas_equalTo([self.textViewsizeThatFits:CGSizeMake(screenWidth - 20, CGFLOAT_MAX)].height);}];

在加载好HTML后,也要设置其高度,但是要注意,sizeThatFits:这个API计算UITextView的高度是不精准的,有一定的误差。

最后

顺便说一下,属性中指定的类型null_resettable是什么鬼?这是新特性啦,从英文角度看就大概可以看出来意思是 可空、可重新设置值

源代码

大家只可以下载本篇文章中所关联的小demo,仅供参考!

下载地址: CoderJackyHuang 欢迎关注笔者的GITHUB地址,关注标哥的技术博客!

关注我

关注 账号 备注
Swift/ObjC技术群一 324400294 群一若已满,请申请群二
Swift/ObjC技术群二 494669518 群二若已满,请申请群三
Swift/ObjC技术群三 461252383 群三若已满,会有提示信息
关注微信公众号 iOSDevShares 关注微信公众号,会定期地推送好文章
关注新浪微博账号 标哥Jacky 关注微博,每次发布文章都会分享到新浪微博
关注标哥的GitHub CoderJackyHuang 这里有很多的Demo和开源组件
关于我 进一步了解标哥 如果觉得文章对您很有帮助,可捐助我!

版权声明:本文为【标哥的技术博客】原创出品,欢迎转载,转载时请注明出处!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the root tag in an HTML document?What is the root tag in an HTML document?Apr 29, 2025 am 12:10 AM

TheroottaginanHTMLdocumentis.Itservesasthetop-levelelementthatencapsulatesallothercontent,ensuringproperdocumentstructureandbrowserparsing.

Are the HTML tags and elements the same thing?Are the HTML tags and elements the same thing?Apr 28, 2025 pm 05:44 PM

The article explains that HTML tags are syntax markers used to define elements, while elements are complete units including tags and content. They work together to structure webpages.Character count: 159

What is the significance of <head> and <body> tag in HTML?What is the significance of <head> and <body> tag in HTML?Apr 28, 2025 pm 05:43 PM

The article discusses the roles of <head> and <body> tags in HTML, their impact on user experience, and SEO implications. Proper structuring enhances website functionality and search engine optimization.

What is the difference between <strong>, <b> tags and <em>, <i> tags?What is the difference between <strong>, <b> tags and <em>, <i> tags?Apr 28, 2025 pm 05:42 PM

The article discusses the differences between HTML tags , , , and , focusing on their semantic vs. presentational uses and their impact on SEO and accessibility.

Please explain how to indicate the character set being used by a document in HTML?Please explain how to indicate the character set being used by a document in HTML?Apr 28, 2025 pm 05:41 PM

Article discusses specifying character encoding in HTML, focusing on UTF-8. Main issue: ensuring correct display of text, preventing garbled characters, and enhancing SEO and accessibility.

What are the various formatting tags in HTML?What are the various formatting tags in HTML?Apr 28, 2025 pm 05:39 PM

The article discusses various HTML formatting tags used for structuring and styling web content, emphasizing their effects on text appearance and the importance of semantic tags for accessibility and SEO.

What is the difference between the 'id' attribute and the 'class' attribute of HTML elements?What is the difference between the 'id' attribute and the 'class' attribute of HTML elements?Apr 28, 2025 pm 05:39 PM

The article discusses the differences between HTML's 'id' and 'class' attributes, focusing on their uniqueness, purpose, CSS syntax, and specificity. It explains how their use impacts webpage styling and functionality, and provides best practices for

What is the 'class' attribute in HTML?What is the 'class' attribute in HTML?Apr 28, 2025 pm 05:37 PM

The article explains the HTML 'class' attribute's role in grouping elements for styling and JavaScript manipulation, contrasting it with the unique 'id' attribute.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.