取消UILongPressGesture

我无法取消UILongPressGesture。 手势连接到一个button,当按下button时,录音机开始录制audio。 当我离开button时,我想让录音停止。 任何帮助表示赞赏,谢谢!

@IBAction func recordAudio(sender: AnyObject) { if sender.state == UIGestureRecognizerState.Ended { session.setCategory(AVAudioSessionCategoryPlayback, error: nil) recorder.stop() recordButton.backgroundColor = UIColor.whiteColor() save() } else if sender.state == UIGestureRecognizerState.Began { session.setCategory(AVAudioSessionCategoryRecord, error: nil) recorder.record() recordButton.backgroundColor = UIColor.greenColor() } else if sender.state == UIGestureRecognizerState.Cancelled { recorder.stop() recordButton.backgroundColor = UIColor.redColor() } } 

编辑 – 拿2

 @IBAction func recordAudio(sender: UILongPressGestureRecognizer) { switch (sender.state) { case .Ended: session.setCategory(AVAudioSessionCategoryPlayback, error: nil) recorder.stop() recordButton.backgroundColor = UIColor.whiteColor() save() case .Began: session.setCategory(AVAudioSessionCategoryRecord, error: nil) recorder.record() recordButton.backgroundColor = UIColor.greenColor() case .Cancelled, .Ended: recorder.stop() recordButton.backgroundColor = UIColor.redColor() default: break } } 

编辑 – 采取3(几乎在那里)

 @IBAction func recordAudio(sender: UILongPressGestureRecognizer) { switch (sender.state) { case .Ended: session.setCategory(AVAudioSessionCategoryPlayback, error: nil) recorder.stop() recordButton.backgroundColor = UIColor.whiteColor() post() case .Began: session.setCategory(AVAudioSessionCategoryRecord, error: nil) recorder.record() recordButton.backgroundColor = UIColor.greenColor() case .Cancelled: recorder.stop() recordButton.backgroundColor = UIColor.redColor() case .Changed: let touchLocation = recordGesture.locationInView(recordButton) if (!CGRectContainsPoint(recordButton.bounds, touchLocation)) { // touch is outside of button recorder.stop() recordButton.backgroundColor = UIColor.whiteColor() break } default: break } } 

这个代码的作品,唯一的问题是。手势已经改变后,仍然被调用,我释放我的手指从屏幕上。

当一个长按手势识别器的触摸移动,然后用状态UIGestureRecognizerStateChanged调用该函数。

我会改变你的代码像这样…

 @IBAction func recordAudio(sender: AnyObject) { switch (sender.state) { case .Ended: session.setCategory(AVAudioSessionCategoryPlayback, error: nil) recorder.stop() recordButton.backgroundColor = .whiteColor() save() case .Began: session.setCategory(AVAudioSessionCategoryRecord, error: nil) recorder.record() recordButton.backgroundColor = .greenColor() case .Cancelled: recorder.stop() recordButton.backgroundColor = .redColor() case .Changed: // detect if the touch has gone outside of the button and stop the recording default: // do nothing } } 

用于检测触摸是否在button内部

你可以做这样的事情

 let touchLocation = recognizer.locationInView(recordButton) if (!CGRectContainsPoint(recordButton.bounds, touchLocation)) { // touch is outside of button } 

没有testing或任何东西。 只需在Safari中键入。