0
NSString *message = @"This part: \"Is in quotations\"";

I'm wondering if it's possible to color the part of the NSString inside the quotations a different color? I understand this example: Is it possible to change color of single word in UITextView and UITextField but not sure how to convert it to my example since I have multiple slahes.

Community
  • 1
  • 1
Apollo
  • 8,874
  • 32
  • 104
  • 192
  • Use NSAttributedString, first get all text range between quotations, then apply it to NSForegroundColorAttributeName – Martin Le May 06 '16 at 04:37

1 Answers1

1

Ive written a xcode playground example (in swift because im lazy) that will colour anything inside quotes

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)

}

result:

coloured text

Im sure it will be easy enough to repurpose it to your needs (and into Obj-c), or can play around with it in your own playground

Fonix
  • 11,447
  • 3
  • 45
  • 74