我有下面的代码,我的长按不工作的方式应该。有人能弄清楚为什么它不起作用吗?

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: "myButton:")
    longPressRecognizer.minimumPressDuration = 0.5
    myButton.addGestureRecognizer(longPressRecognizer)
}

@IBOutlet weak var myButton: UIButton!

@IBAction func myButton(longPress: UILongPressGestureRecognizer) {

    if longPress.state != .Began {

        presentAlertController()

        return
    }
}

当我按下按钮时,就会出现这个错误
2016-01-09 00:41:28.785 longPressTest[1870:551106] Warning: Attempt to present <UIAlertController: 0x144d6a500>  on <longPressTest.ViewController: 0x144e3a450> which is already presenting <UIAlertController: 0x144e59d80>
2016-01-09 00:41:28.903 longPressTest[1870:551106] Attempting to load the view of a view controller while it is deallocating is not allowed and may result in undefined behavior (<UIAlertController: 0x144d6a500>)
2016-01-09 00:41:28.905 longPressTest[1870:551106] Warning: Attempt to present <UIAlertController: 0x144e54bb0>  on <longPressTest.ViewController: 0x144e3a450> which is already presenting <UIAlertController: 0x144e59d80>
Cancel

最佳答案

长按手势是一种连续的手势。这意味着当识别器检测到长按开始时(0.5秒后)用myButton(_:),当触摸在屏幕上移动时用state == .Began重复,当手势结束时用state == .Changed再次调用您的功能(state == .Ended)。您尝试在每个.Changed呼叫和.Ended呼叫上显示警报,并且当您尝试显示已显示的警报时会出现错误。
如果要在0.5秒后立即显示警报,请在状态为.Began时执行,而不是在状态为除.Began以外的任何状态时执行。

@IBAction func myButton(longPress: UILongPressGestureRecognizer) {
    if longPress.state == .Began {
        presentAlertController()
    }
}

您只收到一个状态为.Began的呼叫,因此当警报已经出现时,您不会再次尝试显示警报。

关于ios - 为什么我的UILongPressGestureRecognizer无法正常工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34690068/

10-09 12:27