我在导航栏中有一个UIBarButtonItem。当用户单击它时,它会弹出到另一个viewController。
现在,我希望当用户长按该按钮(导航栏按钮)时,我想显示一条帮助消息。
我需要帮助来分别检测onlick事件和longpress事件。

最佳答案

您应该创建一个按钮,并将UITapGestureRecognizerUILongPressGestureRecognizer设置为您的按钮

// Create a button
let yourButton = UIButton()
yourButton.backgroundColor = .red
yourButton.setTitle("long press", for: .normal)

// Create a tap gesture recognizer
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(didTap))

// Create a long gesture recognizer
let longGesture = UILongPressGestureRecognizer(target: self, action: #selector(long))

// You can set minimum duration of the press action
longGesture.minimumPressDuration = 3 //The default duration is 0.5 seconds.

// Add your gestures to button
yourButton.addGestureRecognizer(longGesture)
yourButton.addGestureRecognizer(tapGesture)

navigationItem.leftBarButtonItem = UIBarButtonItem(customView: yourButton)

@objc private func didTap() {
    print("Did Tap")
}

@objc private func long() {
    // You can show the help message in here
    print("Long press")
}

关于ios - 如何检测UIBarButtonitem中的长按,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60596312/

10-11 21:46