我只有在用户开始平移0.3秒时才能显示一个按钮,以避免在某些情况下瞬间显示按钮(例如,如果手指没有将手指抬起,则在缩放结束时(。为了实现这一目标,我在pan手势处于 .began
状态时启动一个计时器,然后仅在计时器变为nil时仅在 .changed
状态下显示按钮。
但是,直到我抬起手指之前,我的计时器永远不会运行(即手势是.ended
(。我认为这可能与占据主线程的跑步环和手势有关吗?任何解决方法都将不胜感激。谢谢!
var timer: Timer?
func handler(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
if timer == nil {
// I just want timer to invalidate itself after firing, so nothing to execute
self.timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false, block: { _ in })
case .changed:
if button.isHidden && timer == nil {
button.isHidden = false
}
case .ended:
button.isHidden = true
timer?.invalidate()
timer = nil
default:
return
}
}
如果您的主要目标是在用户开始平移0.3秒之后显示按钮,则需要做的就是检测何时移动锅手势,然后显示按钮。您甚至不需要在手势开始时创建计时器。
var timer: Timer?
func handler(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .changed:
if (timer == nil || timer?.isValid == false) {
timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: false) { (_) in
// Show button
self.button.isHidden = false
}
}
case .ended :
button.isHidden = true
timer?.invalidate()
default:
return
}
}
尝试以下:
var timer: Timer?
func handler(_ sender: UIPanGestureRecognizer) {
switch sender.state {
case .began:
if timer == nil {
self.timer = Timer.scheduledTimer(
withTimeInterval: 0.3,
repeats: false,
block: { [weak self] _ in
self?.button.isHidden = false
})
case canceled, .ended:
timer?.invalidate()
timer = nil
default:
return
}
}