【发布时间】:2018-02-23 08:04:55
【问题描述】:
此代码完美运行。
但是我有一个问题,我想加载 HTML 数据并更改它的字体。
我尝试使用 NSAttributedString 来设置 UIFont,它对我不起作用。
我应该怎么做才能更改 HTML 数据字体,并计算它的高度是否正确?
谢谢。
func loadHtmlContent() {
let articleHtmlData = "<head><style>img{width:300px !important;height:225px !important}</style></head>"+articleContent
do {
let attrStr = try NSMutableAttributedString(
data: articleHtmlData.data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
attrStr.enumerateAttribute(
NSFontAttributeName,
in:NSMakeRange(0,attrStr.length),
options:.longestEffectiveRangeNotRequired) { value, range, stop in
let f1 = value as! UIFont
let f2 = UIFont(name:"Helvetica", size:20)!
if let f3 = applyTraitsFromFont(f1, to:f2) {
attrStr.addAttribute(
NSFontAttributeName, value:f3, range:range)
}
}
self.articleHeight = self.heightForHtmlString(attrStr)
self.articleContentTextView.attributedText = attrStr
} catch let error {
print(error)
}
}
func heightForHtmlString(_ text: NSAttributedString) -> CGFloat {
let label:UILabel = UILabel.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.size.width-(16*4), height: CGFloat.greatestFiniteMagnitude))
label.numberOfLines = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.font = UIFont(name: "PingFangTC-Regular", size: 20.0)
label.attributedText = text
label.sizeToFit()
return label.frame.height
}
【问题讨论】:
-
和
label.attributedText一起玩时不要做label.font = UIFont(name: "PingFangTC-Regular", size: 20.0)。仅当您使用label.text时才使用它。 -
改为使用与那里相同的逻辑:stackoverflow.com/a/41413014/1801544 Enumerate the FontAttributeName
-
@Larme (label.font) 它只是计算高度。
-
@Larme 我更新了问题,我使用了 enumerateAttribute 但 textView 没有显示任何内容。
-
只需将
attrStr设为NSMutableAttributeString而不是NSAttributedString(在初始化中)。attrStr.addAttribute(NSFontAttributeName, value:UIFont(name: "PingFangTC-Regular", size: 20.0), range:NSMakeRange(0,attrStr.length))另外,在options:中设置NSFontAttributeName : UIFont.systemFont(ofSize: 20.0)是没有用的,因为它不会被考虑在内(参见该方法的文档)。
标签: ios swift nsattributedstring