2015-09-16 2 views
0

Мое приложение получить HTML форматированный текст с веб-сайта, и я хотел бы изменить размер шрифта NSAttributedString и отобразить его в TextViewИзменить размер шрифта NSAttributedString

var htmlString : String //the html formatted text 
textView.attributedText = handleHtml(htmlString) // this is how I call the function, but the font size didn't change 

func handleHtml(string : String) -> NSAttributedString{ 
    let attrs = [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSFontAttributeName: UIFont.systemFontOfSize(20.0)] 
    var returnStr = NSAttributedString() 
    do { 
     returnStr = try NSAttributedString(data: string.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: attrs, documentAttributes: nil) 
    } catch { 
     print(error) 
    } 
    return returnStr 
} 

Я попытался [NSFontAttributeName: UIFont.systemFontOfSize(20.0)], как показано в выше, но размер шрифта не изменился.

+3

Вы можете изменить шрифт, но добавив некоторые 'NSString' (как HTML) набор, или перебирать окончательной' NSAttributedString' добавить свой шрифт (см есть: HTTP://stackoverflow.com/questions/19921972/parsing-html-into-nsattributedtext-how-to-set-font) Документ 'initWithData: options: documentAttributes: error:' ясно говорит о параметре 'options', который вы можете Нет. – Larme

ответ

1

Я только что понял. Я должен использовать NSMutableAttributedString вместо NSAttributedString

func handleHtml(string : String) -> NSAttributedString{ 
    var returnStr = NSMutableAttributedString() 
    do { 
     returnStr = try NSMutableAttributedString(data: string.dataUsingEncoding(NSUnicodeStringEncoding, allowLossyConversion: true)!, options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) 

     let fullRange : NSRange = NSMakeRange(0, returnStr.length) 
     returnStr.addAttributes([NSFontAttributeName : yourFont], range: fullRange) 

    } catch { 
     print(error) 
    } 
    return returnStr 
} 
Смежные вопросы