我正在使用字符串的这个扩展来从字符串中的 HTML 标记中获取正确的属性文本。
extension String {
var html2AttributedString: NSAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
return try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:NSUTF8StringEncoding ], documentAttributes: nil)
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
我在 UICollectionView
中使用 UILabel
中的值。
if let value = mainNote.html2AttributedString
{
cell.note.attributedText = value
}
else
{
cell.note.text = mainNote
}
这个方法很管用。但默认情况下,它带有大小为 11 的“Times New Roman”字体。所以我想让它大一点。我尝试使用 NSMutableAttributedString
。
if let value = mainNote.html2AttributedString
{
let mutableString = NSMutableAttributedString(string: value.string, attributes: [NSFontAttributeName : UIFont(name: "Times New Roman", size: 20)!])
cell.note.attributedText = mutableString
}
else
{
cell.note.text = mainNote
}
实际上什么也没做。
如果我直接增加 UILabel
的字体大小,那么字体大小会增加,但斜体属性不起作用。
cell.note.font = UIFont(name: "Times New Roman", size: 16)
请帮我把字符串变大一点。
最佳答案
使用这个更新的扩展:
extension String {
func html2AttributedString(font: UIFont?) -> NSAttributedString? {
guard
let data = dataUsingEncoding(NSUTF8StringEncoding)
else { return nil }
do {
let string = try NSAttributedString(data: data, options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding], documentAttributes: nil)
let newString = NSMutableAttributedString(attributedString: string)
string.enumerateAttributesInRange(NSRange.init(location: 0, length: string.length), options: .Reverse) { (attributes : [String : AnyObject], range:NSRange, _) -> Void in
if let font = font {
newString.removeAttribute(NSFontAttributeName, range: range)
newString.addAttribute(NSFontAttributeName, value: font, range: range)
}
}
return newString
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString(nil)?.string ?? ""
}
用法:
if let value = mainNote.html2AttributedString(UIFont(name: "Times New Roman-ItalicMT", size: 20))
{
cell.note.attributedText = value
}
else
{
cell.note.text = mainNote
}
关于ios - NSAttributedString 改变字体大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35216493/