我有以下代码,我的长按不按预期方式工作。任何人都可以找出它无法正常工作的原因吗?
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 :(得分:6)
长按手势是连续手势。这意味着识别器会在myButton(_:)
检测到长按开始(0.5秒后)时调用您的函数(state == .Began
),并且当触摸在{{1当手势以state == .Changed
结束时再次出现。您尝试在每次state == .Ended
来电和.Changed
来电时都会显示提醒,当您尝试提示已经提供的提醒时,您会收到错误。
如果您希望在0.5秒后立即显示提醒,请在状态为.Ended
时显示,而不是状态为除 .Began
时。
.Began
您只能通过状态@IBAction func myButton(longPress: UILongPressGestureRecognizer) {
if longPress.state == .Began {
presentAlertController()
}
}
拨打一个电话,这样您就不会尝试再次显示警报。