如何更改 UITextView 的溢出字符颜色?

How can I change overflowed characters color of my UITextView?

我想要以下结果:

Dream result

我尝试使用此代码,但没有成功:

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

    }
}

我在这个post中看到:Finding index of character in Swift String

我不应该转换为 NSString,因为表情符号可能会出错

PS: 对不起我的英语,我还在学习中。

请使用以下函数来实现您想要的结果。 声明要以默认颜色显示的最大文本长度,除此之外的文本将为红色。

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