1

I would like to have the follow result:

Dream result

I tried to use this code, but no success:

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
    if range.location > 159 {

        let attributedString = NSMutableAttributedString(string: bioTextView.text)

        let range2 = (bioTextView.text as NSString).rangeOfString(bioTextView.text)

        attributedString.addAttributes([NSForegroundColorAttributeName: UIColor.flatRedColor(), NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 14)!], range: range2)

        bioTextView.attributedText = attributedString

    }
}

I saw in this post: Finding index of character in Swift String

That I should not convert to NSString, because can bug with emoji

PS: Sorry about my English, I'm still learning.

Community
  • 1
  • 1
Calebe Emerick
  • 83
  • 1
  • 1
  • 7

1 Answers1

3

Please use following function to achieve your desired result. Declare max length of text that you want to show in default color, other than that text will be red.

func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

let maxLength = 159

if range.location > maxLength {

    let index = textView.text.startIndex.advancedBy(maxLength)

    let mainString = textView.text.substringToIndex(index)

    let mainAttributedString = NSMutableAttributedString (string: mainString, attributes: [NSForegroundColorAttributeName: UIColor.darkGrayColor(), NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 14)!])

    let redAttributedString = NSAttributedString(string: textView.text.substringFromIndex(index), attributes: [NSForegroundColorAttributeName: UIColor.redColor(), NSFontAttributeName: UIFont(name: "Helvetica Neue", size: 14)!])

    mainAttributedString.appendAttributedString(redAttributedString)

    textView.attributedText = mainAttributedString;
  }
}
rushisangani
  • 3,195
  • 2
  • 14
  • 18
  • Thank you so much! It really works! I just added into the code the follow code: `let index = textView.text.startIndex.advancedBy(maxLength).successor()` It's because was painting a character before. – Calebe Emerick Jan 28 '16 at 02:56