将 UIEditMenuInteraction 与 UITextView 结合使用

Has*_*leb 2 uitextview swift ios16

我们如何使用 UIEditMenuInteraction 和 UITextView 来自定义菜单并添加更多按钮?

在 iOS 16 之前我使用的是:

UIMenuController.shared.menuItems = [menuItem1, menuItem2, menuItem3]
Run Code Online (Sandbox Code Playgroud)

RTX*_*mer 6

尝试这个示例源:

class ViewController: UIViewController {
    
    @IBOutlet weak var txtView: UITextView!
    
    var editMenuInteraction: UIEditMenuInteraction?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupEditMenuInteraction()
    }
    
    private func setupEditMenuInteraction() {
        
        // Addding Menu Interaction to TextView
        editMenuInteraction = UIEditMenuInteraction(delegate: self)
        txtView.addInteraction(editMenuInteraction!)
        
        // Addding Long Press Gesture
        let longPressGestureRecognizer =
        UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
        txtView.addGestureRecognizer(longPressGestureRecognizer)
    }
    
    @objc
    func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
        guard gestureRecognizer.state == .began else { return }
        
        let configuration = UIEditMenuConfiguration(
            identifier: "textViewEdit",
            sourcePoint: gestureRecognizer.location(in: txtView)
        )
        
        editMenuInteraction?.presentEditMenu(with: configuration)
    }
}
Run Code Online (Sandbox Code Playgroud)
extension ViewController: UIEditMenuInteractionDelegate {
    func editMenuInteraction(_ interaction: UIEditMenuInteraction,
                             menuFor configuration: UIEditMenuConfiguration,
                             suggestedActions: [UIMenuElement]) -> UIMenu? {
        
        var actions = suggestedActions
        
        let customMenu = UIMenu(title: "", options: .displayInline, children: [
            UIAction(title: "menuItem1") { _ in
                print("menuItem1")
            },
            UIAction(title: "menuItem2") { _ in
                print("menuItem2")
            },
            UIAction(title: "menuItem3") { _ in
                print("menuItem3")
            }
        ])
        
        actions.append(customMenu)
        
        return UIMenu(children: actions) // For Custom and Suggested Menu
        
        return UIMenu(children: customMenu.children) // For Custom Menu Only
    }
}
Run Code Online (Sandbox Code Playgroud)

输出

在此输入图像描述

  • @RTXGamer 请您为 UIEditMenuInteraction 提供一个 Objective-C 示例吗? (2认同)