iosswiftuibuttoncopy-pasteuimenucontroller

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


I create a button that when you hold, it will show the standard ios menu button for pasting a text, but I'm getting an error saying There can only be one UIMenuController instance. when I hold the button 2 times, how can I fix this?

Here is my code

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

Also, how can I listen to the user when he clicked the paste button?

I want it to call this function when he clicked paste.

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

Solution

  • Use the default singleton instance provided (.shared) by UIMenuController instead of creating an instance of your own.

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

    Quoting from apple doc:

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