问题
UITextView自定义文字属性后光标老是自动跳到末尾的问题。
简单来说就是 UITextView.attributedText 赋值富文本有些时候会导致光标跳到最后
解决方案:
去掉下方直接赋值代码
func textViewDidChange(_ textView: UITextView) {
textView.attributedText = addLineSpacing(lineSpacing: 5, originalStr: textView.text)
}
改为
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let attributes = [NSAttributedString.Key.font : font as Any,
NSAttributedString.Key.paragraphStyle : style,
NSAttributedString.Key.foregroundColor: textColor] as [NSAttributedString.Key : Any]
textView.typingAttributes = attributes
return true
}
在didChange中使用 typingAttributes无效
直接修改光标位置,实践中无效
//修改光标位置代码
let range = textView.selectedRange
textView.attributedText = NSAttributedString(string: textView.text, attributes: attributes)
textView.selectedRange = range