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.pswp.cn/news/445717.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/445717.shtml
英文地址,請注明出處:http://en.pswp.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獲取。我們來看具體…

計算機基礎知識整理 手抄報,科技小制作的手抄報資料簡單字少

科學是一切生活的基礎,如同一把鑰匙,為我們開辟前進的道路。科技在我們的生活中也是很重要的。你會做科技手抄報嗎?下面是學習啦小編為大家帶來的有關科技小制作的手抄報,希望大家喜歡。有關科技小制作的手抄報的圖片參考有關科技小制作的手…