计时器永远不会在我的平移手势回调函数中触发

时间:2018-02-09 13:56:13

标签: ios swift timer uipangesturerecognizer runloop

我试图仅在用户开始平移0.3秒时显示按钮,以避免在某些情况下瞬间显示按钮(例如,如果手指未被抬起,则在缩放结束时)。为实现这一点,我在平移手势处于.began状态时启动计时器,然后仅在计时器变为零时显示.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
    }
}

2 个答案:

答案 0 :(得分:0)

如果您的主要目标是在用户开始平移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
    }
}

答案 1 :(得分:-1)

试试这个:

    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
        }
    }