首页 > 解决方案 > 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
         
                
      }

标签: iosswiftperformancetextuitextview

解决方案


似乎您正在为所有模型实例保留imageData: Data 内存。你应该避免这样做。您可以随时创建UIImage实例String (resourceName)

例如,这是我的Assets.xcassets. 在此处输入图像描述

注意:额外的空白将在实现中很有用。

然后你可以这样做 -

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
    }
}

输出

在此处输入图像描述


推荐阅读