gpt4 book ai didi

html - ios textview attributeText加载在设备中工作但不在模拟器中工作的html字体

转载 作者:行者123 更新时间:2023-11-30 12:01:51 26 4
gpt4 key购买 nike

我正在使用 ScrollView 中的 TextView 来加载 html 内容,如下面的代码。在设备上测试时一切正常。但是当我在模拟器上测试时,内容消失了,但您仍然可以复制/粘贴它们。 See the no content image.html 字符串太长时,就会发生这种情况。

当我删除 css "font-family: (font!.fontName); font-size: (font!.pointSize)" 或禁用 "滚动启用时,它将起作用” TextView 。

欢迎任何建议,谢谢!

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)" )
}

最佳答案

这不是显示 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)

关于html - ios textview attributeText加载在设备中工作但不在模拟器中工作的html字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47122968/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com