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
swift解析html数据类型,ios-Swift:以标签或textVi显示HTML数据相关推荐
- iOS Swift 5中的键盘处理
This article was originally published at CometChat. 本文最初在CometChat上发布. "Handling Keyboard in iO ...
- iOS Swift JSON解析教程
In this tutorial, we will learn how to parse a JSON response in our iOS Application using Swift. We ...
- iOS Swift GCD 开发教程
本教程将带你详细了解 GCD 的概念和用法,通过文中的代码示例和附带的 Github 示例工程,可以进一步加深对这些概念的体会.附带的示例工程是一个完整可运行的 App 项目:DispatchQueu ...
- PodfileKit将github上常见的iOS(Swift)第三方框架进行了汇总,并且将框架进行了分类,为用户管理第三方框架提供了方便。
PodfileKit ======================== Easy Podfile ! PodfileKit将github上常见的iOS(Swift)第三方框架进行了汇总,并且将框架进行 ...
- IOS Swift 入门学习汇总 (更新中..)
IOS Swift 学习入门 配置区 info 配置 本地化中文 文件导入Xcode CocoaPads 依赖管理工具 UI区 + 代码 通用 打开新页面方式 设置新开页面全屏展示 跳转页面 正向传值 ...
- Swift学习笔记笔记(一)Swift编程步骤数据类型
一.实验目的: 掌握Swift编程方法. 掌握Swift数据类型. 二.实验原理: playground的界面与使用方法. 常量与变量的定义方法. 3.常量与变量的类型声明方法. 三.实验步骤及内容: ...
- iOS(一):Swift纯代码模式iOS开发入门教程
Swift纯代码模式iOS开发入门教程 项目初始化(修改为纯代码项目) 安装第三方库(以`SnapKit`库为例) 桥接OC库(QMUIKit) 封装视图并进行导航跳转 示例:使用 `TangramK ...
- iOS swift组件化之私有库创建及问题记录
1.进入git创建仓库 2.终端添加spec repo pod repo add xxxxKitSpec https://github.com/xxxx/xxxxKitSpec.git 说明:xxxx ...
- iOS swift Alamofire+HandyJSON网络框架封装
iOS swift Alamofire+HandyJSON网络框架封装 我们在学习Objective_C时使用的网络框架是AFNetworking+MJExtension,而在swift中Alamof ...
最新文章
- linux centos7 升级gcc版本 使用 yum centos-release-scl devtoolset-8-gcc* 非源码编译
- java jar包和war包_java中jar包和war包之间有什么区别
- 《流浪地球》虽好,却存在一个不可回避的硬伤!
- java定义byte_java Byte相关
- Java 基础复习实践 --- Hashcode Equals
- 白盒-CNN纹理深度可视化: 使用MIT Place 场景预训练模型
- java中float%int_java中short、int、long、float、double取值范围
- python安装运行时提示不是内部或外部命令怎么办_如何解决cmd运行python提示不是内部命令...
- [转载]ubuntu 12.10 软件源更新列表
- A股开盘:深证区块链50指数涨0.18%,概念股涨多跌少
- reinterpret_cast、dynamic_cast、static_cast的使用及注意事项
- PLSQL连接本地的Oracle数据库
- php7对redis的扩展及redis主从搭建
- win7系统怎么设置sql服务器,win7系统怎么安装sqlserver2000软件(图文)
- laravel完全安装手册
- c++创建一个linux deamon进程
- 中国经济能否率先复苏
- 【电脑使用】Windows 10账户那些事儿
- 如何把数字金额转换成中文大写
- gif一键抠图 在线_手机一键抠图去背景||电脑抽奖软件
热门文章
- cdh界面 hue 配置hbase_海量数据存储技术之HBase:使用HBase Shell操纵HBase
- linux c++ queue 多线程,C++多线程,消息队列用法
- Azure Blob Storage 基本用法 -- Azure Storage 之 Blob
- 编辑器推荐:Visual Studio Code(VSCode/VSC)
- Callable接口-创建线程的第三种方法
- mysql一对一级联_MySQL 表的一对一、一对多、多对多问题
- 【LeetCode - 42. 接雨水】
- JetBrains - IDEA 常用快捷键汇总
- *【HDU - 4272 】LianLianKan (dfs 或 状压dp,贪心不行)
- *【牛客 - 318B】签到题(单调栈,水题)