[英]NSAttributedString changing the font size
我正在使用String的這個擴展來從String中的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)
請幫我在這里使String變大。
使用此更新的擴展名:
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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.