我在滚动视图中使用文本视图加载html内容,如下面的代码。在设备上进行测试时,一切正常。但是当我在模拟器上进行测试时,内容会消失,但您仍然可以复制/粘贴它们。 See the no content image.当 html字符串太长时会发生这种情况。
当我删除css " font-family:(font!.fontName)时,它会起作用; font-size:(font!.pointSize)" 或禁用文本视图的"滚动启用" 。
欢迎任何建议,谢谢!
let screenWidth = htmlContentTv.frame.width - 10
let font = UIFont(name: "Univers-Light", size: 16)
let html = "<html><head><style>img{max-width:\(screenWidth)px;height:auto !important;width:auto !important;};</style> </head>" + "<body><div style=\"font-family: \(font!.fontName); font-size: \(font!.pointSize);color: #000000; line-height:1.5;\">%@</div></body></html>"
let processHtml = String(format: html, article.content!)
do {
let attrStr = try NSAttributedString(
data: processHtml.data(using:.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSFontAttributeName: font!],
documentAttributes: nil)
htmlContentTv.attributedText = attrStr
} catch let error {
print("html error \(error)" )
}
答案 0 :(得分:0)
这不是显示html文本的好方法,如果你没有明确的理由使用UITextView,你可以在这种情况下使用UIWebView:
webView.loadHTMLString(htmlText, baseURL: nil)
如果您需要更改颜色或字体,可以使用此扩展程序
extension String
{
func htmlFormattedString(font:UIFont, color: UIColor) -> String
{
let numberOfColorComponents:Int = color.cgColor.numberOfComponents
let colorComponents = color.cgColor.components
var colorHexString = ""
if numberOfColorComponents == 4 {
let red = (colorComponents?[0])! * 255
let green = (colorComponents?[1])! * 255
let blue = (colorComponents?[2])! * 255
colorHexString = NSString(format:"%02X%02X%02X", Int(red), Int(green), Int(blue)) as String
} else if numberOfColorComponents == 2 {
let white = (colorComponents?[0])! * 255
colorHexString = NSString(format:"%02X%02X%02X", Int(white), Int(white), Int(white)) as String
} else {
return "Color format noch supported"
}
return NSString(format: "<html>\n <head>\n <style type=\"text/css\">\n body {font-family: \"%@\"; font-size: %@; color:#%@;}\n </style>\n </head>\n <body>%@</body>\n </html>", font.familyName, String(stringInterpolationSegment: font.pointSize), colorHexString, self) as String
}
}
要使用它,只需在将文本加载到WebView
之前调用htmlText.htmlFormattedString(font:someFont,color:.red)
即可