swift解析html数据类型,ios-Swift:以标签或textVi显示HTML数据

ios-Swift:以标签或textVi显示HTML数据

我有一些HTML数据,其中包含标题,段落,图像和列表标签。

有没有一种方法可以在一个UITextView或UILabel中显示此数据?

12个解决方案

146 votes

对于Swift 4:

extension String {

var htmlToAttributedString: NSAttributedString? {

guard let data = data(using: .utf8) else { return NSAttributedString() }

do {

return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)

} catch {

return NSAttributedString()

}

}

var htmlToString: String {

return htmlToAttributedString?.string ?? ""

}

}

然后,每当您要将HTML文本放入UITextView时,请使用:

textView.attributedText = htmlText.htmlToAttributedString

Roger Carvalho answered 2019-11-15T18:40:49Z

34 votes

这是Swift 3版本:

private func getHtmlLabel(text: String) -> UILabel {

let label = UILabel()

label.numberOfLines = 0

label.lineBreakMode = .byWordWrapping

label.attributedString = stringFromHtml(string: text)

return label

}

private func stringFromHtml(string: String) -> NSAttributedString? {

do {

let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)

if let d = data {

let str = try NSAttributedString(data: d,

options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],

documentAttributes: nil)

return str

}

} catch {

}

return nil

}

我在这里找到其他一些答案的问题,花了我一些时间才能正确解决。 我设置了换行模式和行数,以便当HTML跨多行时标签的大小适当。

garie answered 2019-11-15T18:41:20Z

13 votes

添加此扩展名以将您的html代码转换为常规字符串:

extension String {

var html2AttributedString: NSAttributedString? {

guard

let data = dataUsingEncoding(NSUTF8StringEncoding)

else { return nil }

do {

return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding], documentAttributes: nil)

} catch let error as NSError {

print(error.localizedDescription)

return nil

}

}

var html2String: String {

return html2AttributedString?.string ?? ""

}

}

然后在UITextView或UILabel中显示String

textView.text = yourString.html2String或

label.text = yourString.html2String

Himanshu answered 2019-11-15T18:41:56Z

7 votes

Swift 3.0

var attrStr = try! NSAttributedString(

data: "text".data(using: String.Encoding.unicode, allowLossyConversion: true)!,

options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],

documentAttributes: nil)

label.attributedText = attrStr

Ved Rauniyar answered 2019-11-15T18:42:15Z

7 votes

此后,我在更改文本属性时遇到问题,我可以看到其他人问为什么...

因此最好的答案是将扩展名与NSMutableAttributedString结合使用:

extension String {

var htmlToAttributedString: NSMutableAttributedString? {

guard let data = data(using: .utf8) else { return nil }

do {

return try NSMutableAttributedString(data: data,

options: [.documentType: NSMutableAttributedString.DocumentType.html,

.characterEncoding: String.Encoding.utf8.rawValue],

documentAttributes: nil)

} catch let error as NSError {

print(error.localizedDescription)

return nil

}

}

}

然后您可以通过以下方式使用它:

if let labelTextFormatted = text.htmlToAttributedString {

let textAttributes = [

NSAttributedStringKey.foregroundColor: UIColor.white,

NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 13)

] as [NSAttributedStringKey: Any]

labelTextFormatted.addAttributes(textAttributes, range: NSRange(location: 0, length: labelTextFormatted.length))

self.contentText.attributedText = labelTextFormatted

}

Kassy Barb answered 2019-11-15T18:42:52Z

6 votes

我正在使用这个:

extension UILabel {

func setHTML(html: String) {

do {

let attributedString: NSAttributedString = try NSAttributedString(data: html.data(using: .utf8)!, options: [NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType], documentAttributes: nil)

self.attributedText = attributedString

} catch {

self.text = html

}

}

}

Nikolay Khramchenko answered 2019-11-15T18:43:11Z

4 votes

斯威夫特3

extension String {

var html2AttributedString: NSAttributedString? {

guard

let data = data(using: String.Encoding.utf8)

else { return nil }

do {

return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:String.Encoding.utf8], documentAttributes: nil)

} catch let error as NSError {

print(error.localizedDescription)

return nil

}

}

var html2String: String {

return html2AttributedString?.string ?? ""

}

}

Alex Morel answered 2019-11-15T18:43:30Z

2 votes

试试这个:

let label : UILable! = String.stringFromHTML("html String")

func stringFromHTML( string: String?) -> String

{

do{

let str = try NSAttributedString(data:string!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true

)!, options:[NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSNumber(unsignedLong: NSUTF8StringEncoding)], documentAttributes: nil)

return str.string

} catch

{

print("html error\n",error)

}

return ""

}

希望对您有所帮助。

Iyyappan Ravi answered 2019-11-15T18:43:55Z

1 votes

如果您想要HTML,图像和列表,则UILabel不支持此功能。 但是,我发现YYText可以解决问题。

Christopher Kevin Howell answered 2019-11-15T18:44:19Z

1 votes

在UITextView或UILabel中无法显示图像和文本段落,为此,您必须使用UIWebView。

只需将项目添加到情节提要中,链接到您的代码,然后调用它以加载URL。

OBJ-C

NSString *fullURL = @"http://conecode.com";

NSURL *url = [NSURL URLWithString:fullURL];

NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];

[_viewWeb loadRequest:requestObj];

迅速

let url = NSURL (string: "http://www.sourcefreeze.com");

let requestObj = NSURLRequest(URL: url!);

viewWeb.loadRequest(requestObj);

分步教程。[http://sourcefreeze.com/uiwebview-example-using-swift-in-ios/]

Ulysses answered 2019-11-15T18:45:05Z

1 votes

上面的答案在这里是Swift 4.2

extension String {

var htmlToAttributedString: NSAttributedString? {

guard

let data = self.data(using: .utf8)

else { return nil }

do {

return try NSAttributedString(data: data, options: [

NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html,

NSAttributedString.DocumentReadingOptionKey.characterEncoding: String.Encoding.utf8.rawValue

], documentAttributes: nil)

} catch let error as NSError {

print(error.localizedDescription)

return nil

}

}

var htmlToString: String {

return htmlToAttributedString?.string ?? ""

}

}

Stephen Chen answered 2019-11-15T18:45:31Z

-1 votes

如果您具有内含HTML代码的字符串,则可以使用:

extension String {

var utfData: Data? {

return self.data(using: .utf8)

}

var htmlAttributedString: NSAttributedString? {

guard let data = self.utfData else {

return nil

}

do {

return try NSAttributedString(data: data,

options: [

.documentType: NSAttributedString.DocumentType.html,

.characterEncoding: String.Encoding.utf8.rawValue

], documentAttributes: nil)

} catch {

print(error.localizedDescription)

return nil

}

}

var htmlString: String {

return htmlAttributedString?.string ?? self

}

}

并以您的代码使用:

label.text = "something".htmlString

Pedro Menezes answered 2019-11-15T18:46:01Z

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/445717.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

HTML5新增的video标签,HTML5中video标签的使用方法

HTML5中video标签的使用方法发布时间:2020-08-27 11:33:56来源:亿速云阅读:100作者:小新这篇文章将为大家详细讲解有关HTML5中video标签的使用方法,小编觉得挺实用的,因此分享给大家做个参考,希…

开封高级高考2021成绩查询,2021开封市地区高考成绩排名查询,开封市高考各高中成绩喜报榜单...

距离2018年高考还有不到一个月的时间了,很多人在准备最后冲刺的同时,也在关心高考成绩。2018各地区高考成绩排名查询,高考各高中成绩喜报榜单尚未公布,下面是往年各地区高考成绩排名查询,高考各高中成绩喜报榜单,想要了解同学可以…

html 5 笔记,HTML5总笔记(一)

一、p、hn、br标签1.2. :注释。3. :一行,一段(在文字后面直接加)。4.:文字中的最大字符(自动换行)。5. :文字中的最大字符(自动换行)。二、b、i、u、s、su…

【清华大学】《逻辑学概论》笔记

教学视频来源 ----第0讲 概要-0.1 讲师介绍0.2 课程内容--第1讲 什么是逻辑学?-1.1 “逻辑和逻辑学1.2 推理和推理形式1.3 有效推理形式1.4 逻辑学的特点1.5 逻辑学的基本准则1.6 逻辑学和其他学科的关系1.7 关于本课程《逻辑学概论》---第2讲 逻辑学的产生与发展-…

公用计算机管理,如何管理公用计算机和私人计算机的文件访问

如何管理公用计算机和私人计算机的文件访问08/07/2014本文内容适用于: Exchange Server 2007 SP3, Exchange Server 2007 SP2, Exchange Server 2007 SP1, Exchange Server 2007上一次修改主题: 2011-08-01本主题将介绍如何为 Microsoft Exchange Server…

Spring Boot 2 学习笔记(1 / 2)

Spring Boot 2 学习笔记(2 / 2) ---01、基础入门-SpringBoot2课程介绍02、基础入门-Spring生态圈03、基础入门-SpringBoot的大时代背景04、基础入门-SpringBoot官方文档架构05、基础入门-SpringBoot-HelloWorld06、基础入门-SpringBoot-依赖管理特性07、…

关于计算机展览的英语作文,2015考研英语作文范文精选:选什么东西参加展览?...

距离考研初试只剩十几天的时间,备考时间可谓相当紧张,考研英语作文的复习是2015考研考前最后冲刺的重点任务之一,在此分享2015考研英语作文范文精选:选什么东西参加展览?希望能够帮助大家更好的备考。2015考研英语作文范文精选&a…

Spring Boot 2 学习笔记(2 / 2)

Spring Boot 2 学习笔记(1 / 2) ---45、web实验-抽取公共页面46、web实验-遍历数据与页面bug修改47、视图解析-【源码分析】-视图解析器与视图48、拦截器-登录检查与静态资源放行49、拦截器-【源码分析】-拦截器的执行时机和原理50、文件上传-单文件与多…

职校学计算机对口高考可以考幼师吗,幼师专业对口高考考那些

技校网专门为您推荐的类似问题答案问题1:幼师专业对口高考1,幼教要考的内容很多的,比如音乐,舞蹈,心理卫生,教法等等很多的,其中音乐就要考声乐,乐理,视唱等等???2,如…

写出表格的结构html,一个面试题,根据json结构生成html表格

我的输入是{A1: {B1: {C1: {D1: 1233,D2: 11},C2: {D1: 10,D2: 10}},B2: {C1: {D1: 10,D2: 11},C2: {D1: 10,D2: 10},C3: {D1: 10,D2: 10}}}}用什么框架都可以,只要求输出以下table, json的最后一个节点就是table的最后一个column,并且只能占…

how to learn html5,HTML5与CSS基础

你将学到什么How to write a Web pageConcepts of a markup languageBasics of HTML5 and CSSWeb design and stylePage layout and flexbox课程概况This course is part of W3C’s “Front-End Web Developer” Professional Certificate.Learn the basics of Web design and …

单元测试中使用Mockito模拟对象

单元测试应该小巧玲珑,轻盈快捷。然而,一个待测的对象可能依赖另一个对象。它可能需要跟数据库、邮箱服务器、Web Service、消息队列等服务进行交互。但是,这些服务可能在测试过程中不可用。假设这些服务可用,依赖这些服务的单元测…

足球点球 html5,身为西甲第一点球手,C罗只有5次让点经历,难怪点球破门过百...

当今足坛是C罗和梅西的天下,两人持续不断的刷新创造各种记录,让球迷应接不暇。比梅西大2岁的C罗近期更是开挂,今天说他的点球。C罗现在是西甲历史上的第一点球手本赛季西甲第21轮,皇马客场4-1大胜瓦伦西亚,C罗在比赛中…

Spring Cloud 学习笔记(2 / 3)

Spring Cloud 学习笔记(1 / 3) Spring Cloud 学习笔记(3 / 3) ---56_Hystrix之全局服务降级DefaultProperties57_Hystrix之通配服务降级FeignFallback58_Hystrix之服务熔断理论59_Hystrix之服务熔断案例(上)60_Hystrix之服务熔断…

html5的colgroup,HTML colgroup 标签 | 菜鸟教程

HTML 标签实例 和 标签为表格中的三个列设置了背景色:ISBNTitlePrice3476896My first HTML$53尝试一下 浏览器支持所有主流浏览器都支持 标签。标签定义及使用说明 标签用于对表格中的列进行组合,以便对其进行格式化。通过使用 标签,可以向…

Spring Cloud 学习笔记(3 / 3)

Spring Cloud 学习笔记(1 / 3) Spring Cloud 学习笔记(2 / 3) ---108_Nacos之Linux版本安装109_Nacos集群配置(上)110_Nacos集群配置(下)111_Sentinel是什么112_Sentinel下载安装运行113_Sentinel初始化监控114_Sentinel流控规则…

普林斯顿计算机科学系,普林斯顿大学计算机科学系

普林斯顿大学计算机科学系研究生阶段开设有以下学位项目,分别是计算机科学博士:为期5年,要求申请者本科毕业,不限专业背景,但通常被录取的学生拥有工程、理科或数学专业背景,未设定本科GPA要求,…

html5语句大全,html5基础语句(学习)

起风了兼容性问题文档类型设定字符设定常用新标签新增的input type属性值:常用新属性综合案例兼容性问题文档类型设定documentHTMLhttp://blog.sina.com.cn/s/blog_6b38618701011csx.html(html5-api)http://blog.csdn.net/temotemo/article以多维模型为核心&#xf…

html单选按钮for,HTML如何实现RadioButton单选按钮

用HTML来实现RadioButton,需要使用input标签,其中type指定为radio,接下来的文章我们就来说一说详细的内容。我们先来看input标签的格式注:对于需要选中检索的值,可以利用表单的提交或使用JavaScript获取。我们来看具体…

计算机基础知识整理 手抄报,科技小制作的手抄报资料简单字少

科学是一切生活的基础,如同一把钥匙,为我们开辟前进的道路。科技在我们的生活中也是很重要的。你会做科技手抄报吗?下面是学习啦小编为大家带来的有关科技小制作的手抄报,希望大家喜欢。有关科技小制作的手抄报的图片参考有关科技小制作的手…