2016-05-06 11 views
0

Ich frage mich, ob es möglich ist, den Teil der NSString innerhalb der Angebote eine andere Farbe zu färben? Ich verstehe dieses Beispiel: Is it possible to change color of single word in UITextView and UITextField aber nicht sicher, wie man es in mein Beispiel umwandelt, da ich mehrere Slahes habe.Farbe des Textes innerhalb der Notierungen ändern

+0

Verwenden Sie NSAttributedString, zuerst erhalten Sie alle Textbereich zwischen quot und dann auf NSForegroundColorAttributeName anwenden –

Antwort

1

Ive ein Xcode Spielplatz Beispiel (in schnellen, weil im faul) geschrieben, dass irgendetwas in Farbe wird zitiert

var s = "this is a string with \"quotations\" that has multiple \"quotations\" blah blah" 

var split:[String] = s.componentsSeparatedByString("\"") 

var att:NSMutableAttributedString = NSMutableAttributedString() 

for i in 0..<split.count { 

    var temp:NSMutableAttributedString 

    if((i+1)%2 == 0){ //every even index is something between quotations because of how we split 
     temp = NSMutableAttributedString(string: "\"" + split[i] + "\"") 
     temp.addAttribute(NSForegroundColorAttributeName, value: UIColor.greenColor(), range: NSRange(location: 0, length: temp.string.characters.count)) 
    } 
    else { 
     temp = NSMutableAttributedString(string: split[i]) 
     temp.addAttribute(NSForegroundColorAttributeName, value: UIColor.whiteColor(), range: NSRange(location: 0, length: temp.string.characters.count)) 
    } 

    att.appendAttributedString(temp) 

} 

Ergebnis:

coloured text

Ich bin sicher, es wird einfach genug sein, um umfunktionieren es auf Ihre Bedürfnisse (und in Obj-c), oder kann damit auf Ihrem eigenen Spielplatz spielen

Verwandte Themen