与 NSTextAttachment 交互时如何编辑 UITextView 中弹出的上下文菜单

问题描述 投票:0回答:0

我正在尝试实现带有图像附件的

UITextView
。当您长按
NSTextAttachment
中的
UITextView
时,您会看到一个包含一些操作的菜单(例如复制图像、保存到相机胶卷)。我正在尝试做的是在此菜单中添加/编辑选项,就像Apple的笔记应用程序所做的那样。我见过其他笔记应用程序做同样的事情(例如熊应用程序),但我似乎找不到实现或访问它的方法。你能告诉我如何实现吗?

这是我的代码:

import UIKit
import AVFoundation

class ViewController: UIViewController {
    var textView: UITextView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        setUpTextView()
        loadAttributedText()
    }
    
    func setUpTextView() {
        textView = UITextView()
        
        textView.layer.borderColor = UIColor.black.cgColor
        textView.layer.borderWidth = 2
        textView.alwaysBounceVertical = true
        textView.keyboardDismissMode = .interactive
        
        view.addSubview(textView)
        
        //Setup Constarints
        textView.translatesAutoresizingMaskIntoConstraints = false
        textView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor).isActive = true
        textView.leadingAnchor.constraint(equalTo: view.leadingAnchor).isActive = true
        textView.trailingAnchor.constraint(equalTo: view.trailingAnchor).isActive = true
        textView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor).isActive = true
    }
    
    func loadAttributedText() {
        let attributedText = NSMutableAttributedString(string: "This is a sunflower\n")
        
        let image = UIImage(named: "flower")!
        let compressedImage = image.compressImage(to: CGSize(width: 300, height: 400))
        
        let imageAttachment = NSTextAttachment(image: compressedImage)
        let attachmentString = NSAttributedString(attachment: imageAttachment)
        
        attributedText.append(attachmentString)
        attributedText.addAttribute(.font, value: UIFont.systemFont(ofSize: 24, weight: .semibold), range: NSRange(location: 0, length: attributedText.length))
        
        textView.textStorage.setAttributedString(attributedText)
        
    }
}

extension UIImage {
    func compressImage(to maxSize: CGSize) -> UIImage {
        
        let availableRect = AVFoundation.AVMakeRect(aspectRatio: self.size, insideRect: .init(origin: .zero, size: maxSize))
        let targetSize = availableRect.size
        
        let format = UIGraphicsImageRendererFormat()
        format.scale = UIScreen.main.scale
        let renderer = UIGraphicsImageRenderer(size: targetSize, format: format)
        
        let resized = renderer.image { (context) in
            self.draw(in: CGRect(origin: .zero, size: targetSize))
        }
        
        return resized
    }
}

我使用了

UIImage
的扩展来压缩图像以适合 textView 的宽度。

let image = UIImage(named: "flower")!

这里的“花”是我项目资产中的 jpeg 图像。因此,您必须在项目的资产中添加图像并在此处使用它才能进行测试。

我还附上了一些图片来解释问题。

这是我得到的默认行为:

这是我想要的苹果笔记的应用程序行为:

ios swift uiview uikit
© www.soinside.com 2019 - 2024. All rights reserved.