我在取消UILongPressGesture时遇到问题。手势连接到按钮,当按下按钮时,avaudiorecorder开始录制音频。我想要在离开按钮时停止录音。感谢任何帮助,谢谢!
@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
}
}
此代码有效,唯一的问题是。手势发生变化后仍然会调用.Ended,我会从屏幕上释放手指。
答案 0 :(得分:2)
当触摸长按手势识别器移动时,将使用状态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
}
}
用于检测触摸是否在按钮内
你可以这样做......
let touchLocation = recognizer.location(in: recordButton)
if !recordButton.bounds.contains(touchLocation) {
// touch is outside of button
}
未测试或任何其他内容。只需在Safari中徒手打字。