简体   繁体   中英

How can I change overflowed characters color of my UITextView?

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.

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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM