Table of Contents
Demo效果截图
使用到NSAttributedString
UILabel加载HTML
UITextView加载HTML
最后
源代码
关注我
Home Web Front-end HTML Tutorial UITextView和UILabel加载HTML_html/css_WEB-ITnose

UITextView和UILabel加载HTML_html/css_WEB-ITnose

May 25, 2018 pm 01:38 PM

前言

最近有不少朋友们、群友们经常问到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);
Copy after login

其中,options中的指定key为:

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

时,它可以选择的值有:

 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);
Copy after login

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

UILabel加载HTML

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

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

虽然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;
Copy after login

UITextView加载HTML

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

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

与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);}];
Copy after login

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

最后

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

源代码

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

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

关注我

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

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

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Difficulty in updating caching of official account web pages: How to avoid the old cache affecting the user experience after version update? Mar 04, 2025 pm 12:32 PM

The official account web page update cache, this thing is simple and simple, and it is complicated enough to drink a pot of it. You worked hard to update the official account article, but the user still opened the old version. Who can bear the taste? In this article, let’s take a look at the twists and turns behind this and how to solve this problem gracefully. After reading it, you can easily deal with various caching problems, allowing your users to always experience the freshest content. Let’s talk about the basics first. To put it bluntly, in order to improve access speed, the browser or server stores some static resources (such as pictures, CSS, JS) or page content. Next time you access it, you can directly retrieve it from the cache without having to download it again, and it is naturally fast. But this thing is also a double-edged sword. The new version is online,

How do I use HTML5 form validation attributes to validate user input? How do I use HTML5 form validation attributes to validate user input? Mar 17, 2025 pm 12:27 PM

The article discusses using HTML5 form validation attributes like required, pattern, min, max, and length limits to validate user input directly in the browser.

How to efficiently add stroke effects to PNG images on web pages? How to efficiently add stroke effects to PNG images on web pages? Mar 04, 2025 pm 02:39 PM

This article demonstrates efficient PNG border addition to webpages using CSS. It argues that CSS offers superior performance compared to JavaScript or libraries, detailing how to adjust border width, style, and color for subtle or prominent effect

What are the best practices for cross-browser compatibility in HTML5? What are the best practices for cross-browser compatibility in HTML5? Mar 17, 2025 pm 12:20 PM

Article discusses best practices for ensuring HTML5 cross-browser compatibility, focusing on feature detection, progressive enhancement, and testing methods.

What is the purpose of the <datalist> element? What is the purpose of the <datalist> element? Mar 21, 2025 pm 12:33 PM

The article discusses the HTML &lt;datalist&gt; element, which enhances forms by providing autocomplete suggestions, improving user experience and reducing errors.Character count: 159

What is the purpose of the <progress> element? What is the purpose of the <progress> element? Mar 21, 2025 pm 12:34 PM

The article discusses the HTML &lt;progress&gt; element, its purpose, styling, and differences from the &lt;meter&gt; element. The main focus is on using &lt;progress&gt; for task completion and &lt;meter&gt; for stati

How do I use the HTML5 <time> element to represent dates and times semantically? How do I use the HTML5 <time> element to represent dates and times semantically? Mar 12, 2025 pm 04:05 PM

This article explains the HTML5 &lt;time&gt; element for semantic date/time representation. It emphasizes the importance of the datetime attribute for machine readability (ISO 8601 format) alongside human-readable text, boosting accessibilit

What is the purpose of the <meter> element? What is the purpose of the <meter> element? Mar 21, 2025 pm 12:35 PM

The article discusses the HTML &lt;meter&gt; element, used for displaying scalar or fractional values within a range, and its common applications in web development. It differentiates &lt;meter&gt; from &lt;progress&gt; and ex

See all articles