swift - 将 UIEditMenuInteraction 与 UITextView 结合使用

标签 swift uitextview ios16

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

在 iOS 16 之前我使用的是:

UIMenuController.shared.menuItems = [menuItem1, menuItem2, menuItem3]

最佳答案

尝试这个示例源:

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

输出

enter image description here

关于swift - 将 UIEditMenuInteraction 与 UITextView 结合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73712955/

相关文章:

swift - 如何根据字符在 Swift 中修剪字符串

swift - textViewDidChange 函数没有响应

ios - 检测 iOS 键盘上的 Shift + Enter

swift - 如何调整或删除分组的 tableView 标题大小

swift - 如何将 UTF16 字符串解码为 Unicode 字符

ios - 如何防止选择器 View 重复

ios - 具有文本格式的多行 TableView 单元格

ios - 当容器大小发生变化时,考虑到安全区域被忽略,SwiftUI TabView 会失去选择

swiftui - UICalendarView 与 SwiftUI DatePicker NavigationSplitView 侧边栏中的尺寸错误

animation - 禁用方向更改动画