我希望在IOS上的UILabel
上显示格式化的HTML文本。
在Android中,有这样的api:.setText(Html.fromHtml(somestring))
如何在XML中从HTML格式的字符串资源设置TextView文本
我想知道在IOS上是否有相应的功能?
我找到了这个线程:
但是它建议使用UIWebView
。 我需要在每个表格单元格中显示格式化的HTML字符串,因此我认为每行有1个webview
似乎有点重。
有其他替代方案吗?
谢谢。
我希望在IOS上的UILabel
上显示格式化的HTML文本。
在Android中,有这样的api:.setText(Html.fromHtml(somestring))
如何在XML中从HTML格式的字符串资源设置TextView文本
我想知道在IOS上是否有相应的功能?
我找到了这个线程:
但是它建议使用UIWebView
。 我需要在每个表格单元格中显示格式化的HTML字符串,因此我认为每行有1个webview
似乎有点重。
有其他替代方案吗?
谢谢。
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 {
}
try!
,因为可能会抛出异常。 - chengsam对于 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
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
如果您想使用适当缩放(即相对于用户设置)的系统(或其他)字体,可以按照以下步骤操作。
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
var attrStr = NSAttributedString(
data: "<b><i>text</i></b>".dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true),
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil,
error: nil)
label.attributedText = attrStr
无法使用类型为'(data: NSData?, options: [String : String], documentAttributes: _, error: _)'的参数列表调用'NSAttributedString'的初始化程序
- Daniele BObjective-C 版本:
NSError *error = nil;
NSAttributedString *attributedString = [[NSAttributedString alloc] initWithData:contentData
options:@{NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType}
documentAttributes:nil error:&error];
这只是上面答案的Objective-C转换。所有上面的答案都是正确的,参考了上面的答案。
对我来说,Paul的答案起作用了。但是对于自定义字体,我不得不使用以下hack。
//Please take care of force unwrapping
let data = htmlString.data(using: String.Encoding.unicode)!
let mattrStr = try! NSMutableAttributedString(
data: data,
options: [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html],
documentAttributes: nil)
let normalFont = UIFontMetrics.default.scaledFont(for: UIFont(name: "NormalFontName", size: 15.0)!)//
let boldFont = UIFontMetrics.default.scaledFont(for: UIFont(name: "BoldFontName", size: 15.0)!)
mattrStr.beginEditing()
mattrStr.enumerateAttribute(.font, in: NSRange(location: 0, length: mattrStr.length), options: .longestEffectiveRangeNotRequired) { (value, range, _) in
if let oFont = value as? UIFont{
mattrStr.removeAttribute(.font, range: range)
if oFont.fontName.contains("Bold"){
mattrStr.addAttribute(.font, value: boldFont, range: range)
}
else{
mattrStr.addAttribute(.font, value: normalFont, range: range)
}
}
}
Try this:
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 ""
}
Hope its helpful.