2014-12-29 5 views
5

Ich möchte eine Zeichenfolge zu meinem UITextView hinzufügen und ich möchte einige fett und einige in regulärer Schriftart. Wie sollte es das tun? Ich habe ein Beispiel dafür, was ich unten erreichen möchte.UITextView enthält Bold und Regular String

Dank

myTextView.text = "This is my string. " 

Diese ist meine String.

Unten sind die Versuche, die ich gemacht habe.

// 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

zeigen Bitte die Versuche, die Sie bereits bei der Lösung der gemacht haben Problem. –

+0

Der obige Code wurde hinzugefügt. Danke –

+1

In Ordnung, und wie unterscheiden sich die Ergebnisse, die Sie erhalten, von dem, was Sie erwarten? –

Antwort

8

Sehen Sie diesen Code

@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 

Dies ist die Ausgabe: enter image description here

+1

Es zeigt immer noch alles in normalem Text anstelle von einigen fett. Ist das, weil ich ein 'UITextView' verwende? –

+0

Ich habe es auch mit UITextView versucht und es funktioniert. Wie Sie in der aktualisierten Antwort sehen können –

+0

Mein 'UITextView' wird programmatisch erstellt. Wird dies einen Unterschied machen? –