Custom UIMenuController using button event 错误 There can only be one UIMenuController instance

Custom UIMenuController using button event error There can only be one UIMenuController instance

我创建了一个按钮,当您按住该按钮时,它会显示用于粘贴文本的标准 ios 菜单按钮,但是当我按住按钮 2 时出现 There can only be one UIMenuController instance. 错误次,我该如何解决?

这是我的代码

override init(frame: CGRect) {
    super.init(frame: frame)
    self.configureView()
}
    
required init?(coder: NSCoder) {
    super.init(coder: coder)
    self.configureView()
}

private func configureView() {
    guard let view = self.loadViewFromNib(nibName: "CustomView") else { return }
    view.frame = self.bounds
    self.addSubview(view)
        
    button.addTarget(self, action: #selector(holdButton), for: .touchDown)
}

@objc func holdButton(_ sender: UIButton) {
    let menuController = UIMenuController()
    menuController.setTargetRect(sender.frame, in: charTextField)
    menuController.setMenuVisible(true, animated: true)
}

此外,当用户单击 paste 按钮时,我如何听取用户的意见?

我想让他点击paste的时候调用这个函数。

func pasteClick() {
    print("pasted", clipboardString())
}

使用 UIMenuController 提供的默认单例实例 (.shared),而不是创建您自己的实例。

@objc func holdButton(_ sender: UIButton) {
    UIMenuController.shared.setTargetRect(sender.frame, in: charTextField)
    UIMenuController.shared.setMenuVisible(true, animated: true)
}

引用自apple doc

The singleton UIMenuController instance is referred to as the editing menu.....