为什么我的UILongPressGestureRecognizer不起作用?

Joh*_*arp 0 uigesturerecognizer ios swift

我有以下代码,我的长按不按预期方式工作.任何人都可以弄清楚它为什么不起作用?

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
    }
}
Run Code Online (Sandbox Code Playgroud)

当我按住按钮时出现此错误

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 
Run Code Online (Sandbox Code Playgroud)

rob*_*off 6

长按手势是一种连续的手势.这意味着识别器会myButton(_:)在检测到长按开始时(0.5秒后)调用您的函数()state == .Began,并且当触摸在屏幕上移动时重复state == .Changed,并且当手势结束时再次调用state == .Ended.您试图在每次.Changed通话和.Ended通话时显示提醒,当您尝试提示已经提供的提醒时,您会收到错误.

如果您希望在0.5秒后立即显示警报,请在状态为时执行.Began,而不是在状态为除外时执行 .Began.

@IBAction func myButton(longPress: UILongPressGestureRecognizer) {
    if longPress.state == .Began {
        presentAlertController()
    }
}
Run Code Online (Sandbox Code Playgroud)

您只能通过状态拨打一个电话.Began,因此您不会尝试再次显示警报.

  • 也许你可以开始正确拼写我的名字. (2认同)
  • @JohnCarp当你为拼错他的名字而道歉时,我喜欢你拼错Rob的名字.:)(看起来你刚发布这个之后编辑了).仅供参考 - 键入`@`符号,然后输入该用户名的第一个字母.将显示带有一个或多个用户名的工具提示.按Tab键选择一个用于自动填充用户名. (2认同)