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

标签 ios swift 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

    }
}

我在这篇文章中看到: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;
  }
}

关于ios - 如何更改 UITextView 的溢出字符颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35028368/

相关文章:

ios - 触摸时 UITextField 崩溃

iOS 10,QLPreview ViewController 不显示文件

Swift 从初始化程序返回而不初始化所有存储的属性

swift - 将光标位置保持在 textView Swift 的底行

ios - 调试父类(super class)或协议(protocol)扩展/实现时调试嵌入式框架未按预期工作

ios - 比在函数外部使用 var 来跟踪设备方向更好的方法吗?

ios - 将 UITextView 的高度调整为其文本无法正常工作

ios - Google Maps iOS 禁用旋转和倾斜

iOS 11 大型标题更改事件

ios - 清理(​​删除)MagicalRecord 中的数据库