【发布时间】:2021-06-15 09:48:28
【问题描述】:
我是 iOS 的初学者。我想在用户输入时设置 UITextview 属性文本,没关系,但问题是性能滞后,而且太慢。我不知道发生了什么。我将不胜感激您的任何帮助!谢谢
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .left
let alignTextAttributes = [
NSAttributedString.Key.kern : 30,
NSAttributedString.Key.paragraphStyle : paragraphStyle,
NSAttributedString.Key.foregroundColor : UIColor.black,
]
as [NSAttributedString.Key : Any]
let atribute = NSAttributedString(string: text, attributes: alignTextAttributes)
var cursorLocation = textView.selectedRange.location
if text == ""{
textView.textStorage.replaceCharacters(in: range, with: atribute)
cursorLocation -= 1
}else{
textView.textStorage.replaceCharacters(in: range, with: atribute)
cursorLocation += 1
}
textView.selectedRange.location = cursorLocation
//add attachment image to another uitextview
let attachment = NSTextAttachment()
let imageNew = UIImage(named: "icon")
attachment.image = imageNew
let attString = NSAttributedString(attachment: attachment)
txtViewAnother.textStorage.replaceCharacters(in: range, with: attString)
return false
}
【问题讨论】:
-
很伤心没有人帮助我
-
首先,看起来没有使用 var 属性字符串。
-
更进一步,考虑将 alignTextAttributes 存储为类级别属性,而不是在每次用户键入时重新创建它
-
最后,尝试删除光标位置改变的最后一行,看看这是否是导致性能下降的原因。如果是这样,LMK 和我们将是一个解决方案
-
非常感谢@ArikSegal,设置光标位置是问题所在。那么如何在输入普通文本时设置光标位置?
标签: ios swift text attributes uitextview