Swift: 在label或textView中显示HTML数据
Swift: Display HTML data in a label or textView
我有一些 HTML 数据,其中包含标题、段落、图像和列表标签。
有没有办法在 UITextView
或 UILabel
中显示此数据?
试试这个:
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 ""
}
希望对您有所帮助。
添加此扩展以将您的 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 中显示字符串
textView.text = yourString.html2String
或
label.text = yourString.html2String
无法在UITextView
或UILabel
中显示图片和文字段落,为此,您必须使用UIWebView
。
只需将情节提要中的项目 link 添加到您的代码中,然后调用它来加载 URL。
OBJ-C
NSString *fullURL = @"http://conecode.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
Swift
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/
如果您想要 HTML,包含图像和列表,UILabel 不支持。但是,我发现 YYText 可以解决问题。
这里是 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 跨越多行时标签大小适当。
Swift 3.0
var attrStr = try! NSAttributedString(
data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
label.attributedText = attrStr
Swift 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 ?? ""
}
}
我正在使用这个:
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
}
}
}
对于Swift 5:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return nil }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
然后,只要你想在 UITextView 中放置 HTML 文本,请使用:
textView.attributedText = htmlText.htmlToAttributedString
之后我在更改文本属性时遇到了问题,我可以看到其他人问为什么...
所以最好的答案是使用带有 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
}
谢谢上面的答案是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 ?? ""
}
}
如果您有一个包含 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
Swift 5
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil) else { return nil }
return html
}
}
通话:
myLabel.attributedText = "myString".htmlAttributedString()
Swift 5
extension UIColor {
var hexString: String {
let components = cgColor.components
let r: CGFloat = components?[0] ?? 0.0
let g: CGFloat = components?[1] ?? 0.0
let b: CGFloat = components?[2] ?? 0.0
let hexString = String(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)),
lroundf(Float(b * 255)))
return hexString
}
}
extension String {
func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
do {
let htmlCSSString = "<style>" +
"html *" +
"{" +
"font-size: \(size)pt !important;" +
"color: #\(color.hexString) !important;" +
"font-family: \(family ?? "Helvetica"), Helvetica !important;" +
"}</style> \(self)"
guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
return nil
}
return try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
}
最后你可以创建 UILabel:
func createHtmlLabel(with html: String) -> UILabel {
let htmlMock = """
<b>hello</b>, <i>world</i>
"""
let descriprionLabel = UILabel()
descriprionLabel.attributedText = htmlMock.htmlAttributed(family: "YourFontFamily", size: 15, color: .red)
return descriprionLabel
}
结果:
见教程:
https://medium.com/@valv0/a-swift-extension-for-string-and-html-8cfb7477a510
对于Swift5,也可以加载css。
extension String {
public var convertHtmlToNSAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) 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
}
}
public func convertHtmlToAttributedStringWithCSS(font: UIFont? , csscolor: String , lineheight: Int, csstextalign: String) -> NSAttributedString? {
guard let font = font else {
return convertHtmlToNSAttributedString
}
let modifiedString = "<style>body{font-family: '\(font.fontName)'; font-size:\(font.pointSize)px; color: \(csscolor); line-height: \(lineheight)px; text-align: \(csstextalign); }</style>\(self)";
guard let data = modifiedString.data(using: .utf8) else {
return nil
}
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
}
catch {
print(error)
return nil
}
}
}
之后,转到要转换为 NSAttributedString 的字符串并将其放置在下面的示例中:
myUILabel.attributedText = "Swift is awesome!!!".convertHtmlToAttributedStringWithCSS(font: UIFont(name: "Arial", size: 16), csscolor: "black", lineheight: 5, csstextalign: "center")
以下是每个参数的内容:
- 字体:像往常一样在 UILabel/UITextView 中添加字体,使用带有自定义字体名称和大小的 UIFont。
- css颜色:以十六进制格式添加颜色,如“#000000”或使用颜色名称,如"black".
- 行高:UILabel/UITextView.
中有多行时,行间的space
- csstextalign:是文本的对齐方式,需要加上的值为"left"或"right"或"center"或"justify"
我知道这看起来有点夸张,但是...此代码将为 UILabel、UITextView、UIButton 和 [=13= 添加 html 支持]您可以轻松地将此支持添加到具有属性字符串支持的任何视图:
public protocol CSHasAttributedTextProtocol: AnyObject {
func attributedText() -> NSAttributedString?
func attributed(text: NSAttributedString?) -> Self
}
extension UIButton: CSHasAttributedTextProtocol {
public func attributedText() -> NSAttributedString? {
attributedTitle(for: .normal)
}
public func attributed(text: NSAttributedString?) -> Self {
setAttributedTitle(text, for: .normal); return self
}
}
extension UITextView: CSHasAttributedTextProtocol {
public func attributedText() -> NSAttributedString? { attributedText }
public func attributed(text: NSAttributedString?) -> Self { attributedText = text; return self }
}
extension UILabel: CSHasAttributedTextProtocol {
public func attributedText() -> NSAttributedString? { attributedText }
public func attributed(text: NSAttributedString?) -> Self { attributedText = text; return self }
}
public extension CSHasAttributedTextProtocol
where Self: CSHasFontProtocol, Self: CSHasTextColorProtocol {
@discardableResult
func html(_ text: String) -> Self { html(text: text) }
@discardableResult
func html(text: String) -> Self {
let html = """
<html><body style="color:\(textColor!.hexValue()!);
font-family:\(font()!.fontName);
font-size:\(font()!.pointSize);">\(text)</body></html>
"""
html.data(using: .unicode, allowLossyConversion: true).notNil { data in
attributed(text: try? NSAttributedString(data: data, options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)
], documentAttributes: nil))
}
return self
}
}
public protocol CSHasFontProtocol: AnyObject {
func font() -> UIFont?
func font(_ font: UIFont?) -> Self
}
extension UIButton: CSHasFontProtocol {
public func font() -> UIFont? { titleLabel?.font }
public func font(_ font: UIFont?) -> Self { titleLabel?.font = font; return self }
}
extension UITextView: CSHasFontProtocol {
public func font() -> UIFont? { font }
public func font(_ font: UIFont?) -> Self { self.font = font; return self }
}
extension UILabel: CSHasFontProtocol {
public func font() -> UIFont? { font }
public func font(_ font: UIFont?) -> Self { self.font = font; return self }
}
public protocol CSHasTextColorProtocol: AnyObject {
func textColor() -> UIColor?
func text(color: UIColor?) -> Self
}
extension UIButton: CSHasTextColorProtocol {
public func textColor() -> UIColor? { titleColor(for: .normal) }
public func text(color: UIColor?) -> Self { setTitleColor(color, for: .normal); return self }
}
extension UITextView: CSHasTextColorProtocol {
public func textColor() -> UIColor? { textColor }
public func text(color: UIColor?) -> Self { textColor = color; return self }
}
extension UILabel: CSHasTextColorProtocol {
public func textColor() -> UIColor? { textColor }
public func text(color: UIColor?) -> Self { textColor = color; return self }
}
extension UITextView {
func setHTMLFromString(htmlText: String) {
let modifiedFont = String(format:"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: \(self.font!.pointSize)\">%@</span>", htmlText)
let attrStr = try! NSAttributedString(
data: modifiedFont.data(using: .utf8, allowLossyConversion: true)!,
options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue],
documentAttributes: nil)
self.attributedText = attrStr
}
}
我有一些 HTML 数据,其中包含标题、段落、图像和列表标签。
有没有办法在 UITextView
或 UILabel
中显示此数据?
试试这个:
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 ""
}
希望对您有所帮助。
添加此扩展以将您的 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 中显示字符串
textView.text = yourString.html2String
或
label.text = yourString.html2String
无法在UITextView
或UILabel
中显示图片和文字段落,为此,您必须使用UIWebView
。
只需将情节提要中的项目 link 添加到您的代码中,然后调用它来加载 URL。
OBJ-C
NSString *fullURL = @"http://conecode.com";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[_viewWeb loadRequest:requestObj];
Swift
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/
如果您想要 HTML,包含图像和列表,UILabel 不支持。但是,我发现 YYText 可以解决问题。
这里是 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 跨越多行时标签大小适当。
Swift 3.0
var attrStr = try! NSAttributedString(
data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
label.attributedText = attrStr
Swift 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 ?? ""
}
}
我正在使用这个:
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
}
}
}
对于Swift 5:
extension String {
var htmlToAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) else { return nil }
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
return nil
}
}
var htmlToString: String {
return htmlToAttributedString?.string ?? ""
}
}
然后,只要你想在 UITextView 中放置 HTML 文本,请使用:
textView.attributedText = htmlText.htmlToAttributedString
之后我在更改文本属性时遇到了问题,我可以看到其他人问为什么...
所以最好的答案是使用带有 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
}
谢谢上面的答案是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 ?? ""
}
}
如果您有一个包含 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
Swift 5
extension String {
func htmlAttributedString() -> NSAttributedString? {
guard let data = self.data(using: String.Encoding.utf16, allowLossyConversion: false) else { return nil }
guard let html = try? NSMutableAttributedString(
data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil) else { return nil }
return html
}
}
通话:
myLabel.attributedText = "myString".htmlAttributedString()
Swift 5
extension UIColor {
var hexString: String {
let components = cgColor.components
let r: CGFloat = components?[0] ?? 0.0
let g: CGFloat = components?[1] ?? 0.0
let b: CGFloat = components?[2] ?? 0.0
let hexString = String(format: "#%02lX%02lX%02lX", lroundf(Float(r * 255)), lroundf(Float(g * 255)),
lroundf(Float(b * 255)))
return hexString
}
}
extension String {
func htmlAttributed(family: String?, size: CGFloat, color: UIColor) -> NSAttributedString? {
do {
let htmlCSSString = "<style>" +
"html *" +
"{" +
"font-size: \(size)pt !important;" +
"color: #\(color.hexString) !important;" +
"font-family: \(family ?? "Helvetica"), Helvetica !important;" +
"}</style> \(self)"
guard let data = htmlCSSString.data(using: String.Encoding.utf8) else {
return nil
}
return try NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil)
} catch {
print("error: ", error)
return nil
}
}
}
最后你可以创建 UILabel:
func createHtmlLabel(with html: String) -> UILabel {
let htmlMock = """
<b>hello</b>, <i>world</i>
"""
let descriprionLabel = UILabel()
descriprionLabel.attributedText = htmlMock.htmlAttributed(family: "YourFontFamily", size: 15, color: .red)
return descriprionLabel
}
结果:
见教程:
https://medium.com/@valv0/a-swift-extension-for-string-and-html-8cfb7477a510
对于Swift5,也可以加载css。
extension String {
public var convertHtmlToNSAttributedString: NSAttributedString? {
guard let data = data(using: .utf8) 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
}
}
public func convertHtmlToAttributedStringWithCSS(font: UIFont? , csscolor: String , lineheight: Int, csstextalign: String) -> NSAttributedString? {
guard let font = font else {
return convertHtmlToNSAttributedString
}
let modifiedString = "<style>body{font-family: '\(font.fontName)'; font-size:\(font.pointSize)px; color: \(csscolor); line-height: \(lineheight)px; text-align: \(csstextalign); }</style>\(self)";
guard let data = modifiedString.data(using: .utf8) else {
return nil
}
do {
return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
}
catch {
print(error)
return nil
}
}
}
之后,转到要转换为 NSAttributedString 的字符串并将其放置在下面的示例中:
myUILabel.attributedText = "Swift is awesome!!!".convertHtmlToAttributedStringWithCSS(font: UIFont(name: "Arial", size: 16), csscolor: "black", lineheight: 5, csstextalign: "center")
- 字体:像往常一样在 UILabel/UITextView 中添加字体,使用带有自定义字体名称和大小的 UIFont。
- css颜色:以十六进制格式添加颜色,如“#000000”或使用颜色名称,如"black".
- 行高:UILabel/UITextView. 中有多行时,行间的space
- csstextalign:是文本的对齐方式,需要加上的值为"left"或"right"或"center"或"justify"
我知道这看起来有点夸张,但是...此代码将为 UILabel、UITextView、UIButton 和 [=13= 添加 html 支持]您可以轻松地将此支持添加到具有属性字符串支持的任何视图:
public protocol CSHasAttributedTextProtocol: AnyObject {
func attributedText() -> NSAttributedString?
func attributed(text: NSAttributedString?) -> Self
}
extension UIButton: CSHasAttributedTextProtocol {
public func attributedText() -> NSAttributedString? {
attributedTitle(for: .normal)
}
public func attributed(text: NSAttributedString?) -> Self {
setAttributedTitle(text, for: .normal); return self
}
}
extension UITextView: CSHasAttributedTextProtocol {
public func attributedText() -> NSAttributedString? { attributedText }
public func attributed(text: NSAttributedString?) -> Self { attributedText = text; return self }
}
extension UILabel: CSHasAttributedTextProtocol {
public func attributedText() -> NSAttributedString? { attributedText }
public func attributed(text: NSAttributedString?) -> Self { attributedText = text; return self }
}
public extension CSHasAttributedTextProtocol
where Self: CSHasFontProtocol, Self: CSHasTextColorProtocol {
@discardableResult
func html(_ text: String) -> Self { html(text: text) }
@discardableResult
func html(text: String) -> Self {
let html = """
<html><body style="color:\(textColor!.hexValue()!);
font-family:\(font()!.fontName);
font-size:\(font()!.pointSize);">\(text)</body></html>
"""
html.data(using: .unicode, allowLossyConversion: true).notNil { data in
attributed(text: try? NSAttributedString(data: data, options: [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: NSNumber(value: String.Encoding.utf8.rawValue)
], documentAttributes: nil))
}
return self
}
}
public protocol CSHasFontProtocol: AnyObject {
func font() -> UIFont?
func font(_ font: UIFont?) -> Self
}
extension UIButton: CSHasFontProtocol {
public func font() -> UIFont? { titleLabel?.font }
public func font(_ font: UIFont?) -> Self { titleLabel?.font = font; return self }
}
extension UITextView: CSHasFontProtocol {
public func font() -> UIFont? { font }
public func font(_ font: UIFont?) -> Self { self.font = font; return self }
}
extension UILabel: CSHasFontProtocol {
public func font() -> UIFont? { font }
public func font(_ font: UIFont?) -> Self { self.font = font; return self }
}
public protocol CSHasTextColorProtocol: AnyObject {
func textColor() -> UIColor?
func text(color: UIColor?) -> Self
}
extension UIButton: CSHasTextColorProtocol {
public func textColor() -> UIColor? { titleColor(for: .normal) }
public func text(color: UIColor?) -> Self { setTitleColor(color, for: .normal); return self }
}
extension UITextView: CSHasTextColorProtocol {
public func textColor() -> UIColor? { textColor }
public func text(color: UIColor?) -> Self { textColor = color; return self }
}
extension UILabel: CSHasTextColorProtocol {
public func textColor() -> UIColor? { textColor }
public func text(color: UIColor?) -> Self { textColor = color; return self }
}
extension UITextView {
func setHTMLFromString(htmlText: String) {
let modifiedFont = String(format:"<span style=\"font-family: '-apple-system', 'HelveticaNeue'; font-size: \(self.font!.pointSize)\">%@</span>", htmlText)
let attrStr = try! NSAttributedString(
data: modifiedFont.data(using: .utf8, allowLossyConversion: true)!,
options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue],
documentAttributes: nil)
self.attributedText = attrStr
}
}