我想得到如下结果:
我尝试使用这段代码,但没有成功:
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/