2016-05-31 1 views
0

ラベルに属性を設定しています。コードが の下に書き込まれています。唯一の問題は、フォントと色がラベルに描画されないことです。アトリビュートされていない文字列がラベル上で動作していない

func setDataWithContent(content: EmbeddedContent) { 

     if let htmlString = content.text { 
      do { 
       let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)! 
       let attributedOptions : [String: AnyObject] = [ 
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
        NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding, 
        NSFontAttributeName: UIFont(name: "SourceSansPro-Regular", size:16)!, 
        NSForegroundColorAttributeName: UIColor.redColor() 
       ] 
       let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) 
       htmlTextLabel.attributedText = attributedString 

      } catch { 
       fatalError("Error: \(error)") 
      } 
     } 

    } 

誰でも手助けできますか?

+1

これは正常です。 'NSAttributedString(data:options:documentsAttributes:)'のドキュメントを見てください。 'NSFontAttributeName'と' NSForegroundColorAttributeName'は無視されます。その後、 'attributedString'(後で' NSMutableAttributedString'を使ってその属性を変更することができます)に戻ります。 – Larme

+0

http://stackoverflow.com/questions/27728466/use-multiple-font-colors-in-a-single-label-swift/27728516#27728516 –

答えて

1

NSAttributedString(data:options:documentsAttributes)は、オプションでNSFontAttributeNameNSForegroundColorAttributeNameをサポートしていません。 これらは無視されます。

だから、あなたはNSMutableAttributedStringを使用する必要があり、その後、独自のエフェクトを追加します。

let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)! 

let attributedOptions : [String: AnyObject] = [ 
    NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, 
    NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding 
] 
let attributedString = try NSMutableAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) 
let addedEffects:[String:AnyObject] = [          
    NSFontAttributeName: UIFont(name: "SourceSansPro-Regular", size:16)!, 
    NSForegroundColorAttributeName: UIColor.redColor() 
] 
attributedString.addAttributes(addedEffects, range:NSRange(location:0,length:attributedString.length) 
htmlTextLabel.attributedText = attributedString 

注:それはコンパイルする場合、私は知らないが、あなたのアイデアを取得する必要があります。

私は問題を理解するための「迅速な方法」を持っているが、明らかに重複しており、そのようにフラグが立っていれば幸いに回答を削除します。

+0

この回答は承認後に削除することはできません。 – JAL

+0

おっと、期待していませんでした。 OPはその問題を重複としてマークするとも考えました。 – Larme

関連する問題