2016-08-24 64 views
2

我有這樣的代碼在我的手裏:如何使粗體成爲NSMutableString的一部分?

if let text = trimText?.mutableCopy() as? NSMutableString { 
    text.insertString("\(prefix) ", atIndex: 0) 
    textStorage.replaceCharactersInRange(range, withString: text as String) 
} 

當我試圖改變我的text爲:

text = attributedTextFunc(text) 

其中

func attributedTextFunc(str: NSString) -> NSAttributedString { 

    var attributedString = NSMutableAttributedString(string: str as String, attributes: [NSFontAttributeName:UIFont.systemFontOfSize(15.0)]) 

    let boldFontAttribute = [NSFontAttributeName: UIFont.boldSystemFontOfSize(15.0)] 

    attributedString.addAttributes(boldFontAttribute, range: str.rangeOfString("More")) 

    return attributedString 
} 

,我得到這個錯誤:

Cannot assign value of type 'NSAttributedString' to type 'NSMutableString' 

我怎樣才能使它大膽?

回答

2

你不能將NSAttributedString分配給文本。這是兩種不同的類型。

字符串不是NSAttributedString的子類。

您應該設置:

attributedText = attributedTextFunc(text) 

然後,如果你想提出它的UILabel

label.attributedText = attributedText 

UPDATE

結構String不知道的UIKit和大膽風格的東西。

NSAttributedString知道的UIKit和包含要

更新2

任何文本樣式在你的情況

ReadMoreTextView.attributedTrimText = attributedText 
+0

我使用這個庫https://github.com/ilyapuchka/ReadMoreTextView,我想改變修剪文本顏色和使其大膽。但是我不能=/ – Doe

+0

是的,你應該在這個庫裏面做。 – Konstantin

+0

@Doe你想要大膽'閱讀更多'文本? –

0

這是因爲,你的text是的NSMutableString和你的函數的類型attributedTextFunc是NSString類型。

這就是問題所以只需將其從NSString更改爲NSMutableString。

+0

NSMutableString是NSString的子類,問題在NSAttributedString中。 NSAttributedString不是NSString的子類 – Konstantin

2

你不能重新分配text因爲:

  • text是恆定的(let
  • textNSMutableString,但attributedTextFunc回報NSAttributedString

你必須在變量中存儲的attributedTextFunc結果作爲NSAttributeString並設置attributeTextUILabel ins的text

if let text = trimText?.mutableCopy() as? NSMutableString { 
    // ... 
    let attributeText = attributedTextFunc(text) 
    someLabel.attributeText = attributeText 
} 
0

使用此代碼,並通過TEAD你正常的字符串和大膽的字符串(這是需要大膽)。

func attributeStrings(first: String, second : String) -> NSMutableAttributedString{ 
     let myNormalAttributedTitle = NSAttributedString(string: first, 
                 attributes: [NSFontAttributeName : UIFont.boldSystemFontOfSize(15)]) 
     let myAttributedTitle = NSAttributedString(string: second, 
                attributes: [NSForegroundColorAttributeName : UIColor.blackColor()]) 
     let result = NSMutableAttributedString() 
     result.appendAttributedString(myNormalAttributedTitle) 
     result.appendAttributedString(myAttributedTitle) 
     return result 
    } 

而這個函數的返回值賦給

someLabel.attributeText = attributeStrings("My Name is", second : "Himanshu") 
相關問題