UITextView和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和开源组件 |
关于我 | 进一步了解标哥 | 如果觉得文章对您很有帮助,可捐助我! |
版权声明:本文为【标哥的技术博客】原创出品,欢迎转载,转载时请注明出处!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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,

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

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

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

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

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

This article explains the HTML5 <time> 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

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