hap*_*497 43 html uiwebview uilabel ios swift
我想在IOS中显示html格式的文本UILabel.
在Android中,它有这样的api .setText(Html.fromHtml(somestring));
从XML格式的html格式的字符串资源中设置TextView文本
我想知道ios中是否有相同的内容?
我搜索并找到这个帖子:
但它建议使用UIWebView.我需要在每个表格单元格中显示html格式的字符串,所以我认为webview每行1 个看起来有点沉重.
那还有其他选择吗?
谢谢.
ƒer*_*lle 53
Swift 3.0
do {
let attrStr = try NSAttributedString(
data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
label.attributedText = attrStr
} catch let error {
}
Run Code Online (Sandbox Code Playgroud)
Dan*_*e B 48
对于Swift 2.0:
var attrStr = try! NSAttributedString(
data: "<b><i>text</i></b>".dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
label.attributedText = attrStr
Run Code Online (Sandbox Code Playgroud)
Con*_*nor 21
你可以尝试一个属性字符串:
var attrStr = NSAttributedString(
data: "<b><i>text</i></b>".dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
label.attributedText = attrStr
Run Code Online (Sandbox Code Playgroud)
Pau*_*l B 18
import UIKit
let htmlString = "<html><body> Some <b>html</b> string </body></html>"
// works even without <html><body> </body></html> tags, BTW
let data = htmlString.data(using: String.Encoding.unicode)! // mind "!"
let attrStr = try? NSAttributedString( // do catch
data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil)
// suppose we have an UILabel, but any element with NSAttributedString will do
label.attributedText = attrStr
Run Code Online (Sandbox Code Playgroud)
要使用正确缩放(即相对于用户设置)系统(或任何其他)字体,您可以执行以下操作.
let newFont = UIFontMetrics.default.scaledFont(for: UIFont.systemFont(ofSize: UIFont.systemFontSize)) // The same is possible for custom font.
let mattrStr = NSMutableAttributedString(attributedString: attrStr!)
mattrStr.beginEditing()
mattrStr.enumerateAttribute(.font, in: NSRange(location: 0, length: mattrStr.length), options: .longestEffectiveRangeNotRequired) { (value, range, _) in
if let oFont = value as? UIFont, let newFontDescriptor = oFont.fontDescriptor.withFamily(newFont.familyName).withSymbolicTraits(oFont.fontDescriptor.symbolicTraits) {
let nFont = UIFont(descriptor: newFontDescriptor, size: newFont.pointSize)
mattrStr.removeAttribute(.font, range: range)
mattrStr.addAttribute(.font, value: nFont, range: range)
}
}
mattrStr.endEditing()
label.attributedText = mattrStr
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50084 次 |
| 最近记录: |