<分区>
我有一个 textView,我想给它一个属性文本。我尝试在 shouldChangeTextInRange
中实现它,但它因超出索引范围而崩溃。
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
if myTextView {
textView.attributedText = addAttributedText(1, text: text, fontsize: 13)
let newText = (textView.text as NSString).stringByReplacingCharactersInRange(range, withString: text)
let numberOfChars = newText.characters.count
return numberOfChars < 20
}
return true
}
func addAttributedText(spacing:CGFloat, text:String, fontsize: CGFloat) -> NSMutableAttributedString {
let attributedString = NSMutableAttributedString(string: text, attributes: [NSFontAttributeName:UIFont(
name: "Font",
size: fontsize)!])
attributedString.addAttribute(NSKernAttributeName, value: spacing, range: NSMakeRange(0, text.characters.count))
return attributedString
}
我尝试将带有空文本的 attributedString 添加到 viewDidLoad 中的 textView,但这没有帮助。这就是为什么我认为在 shouldChangeTextInRange
(请注意,我的 addAttributedText
方法对其他 TextView 非常有效)
如果我使用它,在输入一个字符时,它会写入 2x 并崩溃。处理将 textView 的文本转换为正在键入的属性文本的正确方法是什么。