2014-12-29 86 views
5

我想向我的UITextView添加一個字符串,我希望有一些字體是粗體和一些常規字體。它應該如何做到這一點?我有一個我想要在下面實現的例子。UITextView包含粗體和常規字符串

感謝

myTextView.text = "This is my string. " 

以下是我所做的嘗試。

// Define string attributes 
    let font = UIFont(name: "Georgia", size: 18.0) ?? UIFont.systemFontOfSize(18.0) 
    let textFont = [NSFontAttributeName:font] 

    let fontItal = UIFont(name: "Georgia-Italic", size: 40.0) ?? UIFont.systemFontOfSize(40.0) 
    let italFont = [NSFontAttributeName:fontItal] 

    // Create a string that will be our paragraph 
    let para = NSMutableAttributedString() 

    // Create locally formatted strings 
    let attrString1 = NSAttributedString(string: "This is ", attributes:textFont) 
    let attrString2 = NSAttributedString(string: "my", attributes:italFont) 
    let attrString3 = NSAttributedString(string: " string.", attributes:textFont) 

    // Add locally formatted strings to paragraph 
    para.appendAttributedString(attrString1) 
    para.appendAttributedString(attrString2) 
    para.appendAttributedString(attrString3) 

    // Define paragraph styling 
    let paraStyle = NSMutableParagraphStyle() 
    paraStyle.firstLineHeadIndent = 15.0 
    paraStyle.paragraphSpacingBefore = 10.0 

    // Apply paragraph styles to paragraph 
    para.addAttribute(NSParagraphStyleAttributeName, value: paraStyle, range: NSRange(location: 0,length: para.length)) 


    // Add string to UITextView 

    myTextView.attributedText = para 
+0

請表明你在解決已經作出的努力問題。 –

+0

添加了上面的代碼。謝謝 –

+1

好吧,您收到的結果與您期望的結果有何不同? –

回答

8

看到這個代碼

@IBOutlet weak var textField: UITextField! 
@IBOutlet weak var textView: UITextView! 

...

var text: NSString = "This is my string" 
var attributedText: NSMutableAttributedString = NSMutableAttributedString(string: text) 

attributedText.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(14)], range: NSRange(location: 5, length: 2)) 
attributedText.addAttributes([NSFontAttributeName: UIFont.boldSystemFontOfSize(14)], range: NSRange(location: 11, length: 6)) 

textField.attributedText = attributedText 
textView.attributedText = attributedText 

這是輸出: enter image description here

+1

它仍然以普通文本而不是粗體顯示。這是因爲我使用了'UITextView'嗎? –

+0

我試過它與UITextView以及它的作品。正如你可以在更新的答案 –

+0

中看到的,我的'UITextView'是以編程方式創建的。這會有所作爲嗎? –