我想得到以下结果:
我尝试使用此代码,但没有成功:
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:对不起我的英语,我还在学习。
答案 0 :(得分:4)
请使用以下功能来达到理想的效果。 声明要以默认颜色显示的文本的最大长度,除了该文本将为红色。
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;
}
}