ios - UITextView 设置 NSTextAttachment 图像导致性能滞后、缓慢问题
问题描述
我想在用户输入时向 UITextview 添加图像附件,这很好用,但问题是 CPU 的增长与添加的图像附件数量一样多。90%。并导致 UI 滞后等缓慢。我已将图像调整为小尺寸,但问题仍然存在。这是我在做什么的图像
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
for data in arrDataModel {
if data.textDefaul == text {
let attachment = NSTextAttachment()
if let image = data.imageData {
let imageNew = UIImage(data: image)!
attachment.image = imageNew
let attString = NSAttributedString(attachment: attachment)
txtViewShow.textStorage.replaceCharacters(in: range, with: attString)
}
break
}
}
return true
}
解决方案
似乎您正在为所有模型实例保留imageData: Data
内存。你应该避免这样做。您可以随时创建UIImage
实例String (resourceName)
。
注意:额外的空白将在实现中很有用。
然后你可以这样做 -
class ViewController: UIViewController, UITextViewDelegate {
let alphabets = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M",
"N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
struct AlphabetInfo {
let alphabet: String
var image: UIImage? {
UIImage(named: "alphabet_\(alphabet)")
}
}
lazy var alphabetInfos: [AlphabetInfo] = {
alphabets.map { AlphabetInfo(alphabet: $0) }
}()
func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
for info in alphabetInfos {
if info.alphabet == text.uppercased() {
if let image = info.image {
let attachment = NSTextAttachment()
attachment.image = image
attachment.bounds = CGRect(origin: .zero, size: CGSize(width: 60, height: 60))
let attachmentString = NSAttributedString(attachment: attachment)
textView.textStorage.replaceCharacters(in: range, with: attachmentString)
}
break
}
}
var cursorLocation = textView.selectedRange.location
if text.isEmpty {
textView.textStorage.replaceCharacters(in: range, with: text)
cursorLocation -= range.length
} else {
cursorLocation += text.count
}
textView.selectedRange.location = cursorLocation
return false
}
}
输出
推荐阅读
- c++ - 三个或更多字符串的 cout 排列
- slack-api - Slack-API:DM 的 /conversations.list api 响应字段“优先级”。它代表什么?
- kubernetes - 每次升级伞形图表时,Helm 子图表升级前挂钩都会运行
- heartbeat - 如何获取心电图记录?
- scroll - 如何 React Native 应用程序在平面列表滚动上加载更多数据达到顶部
- javascript - LitElement 替换组件内的内容
- svelte - Svelte:如何等待组件渲染
- javascript - 无法将 js 文件导入到 component.ts
- c# - 在彼此下方创建矩形
- c++ - 如何向数组添加越来越多的内容