Int值坚持

时间:2016-04-21 08:17:12

标签: iphone swift swift2 nstimer ios9.2

我想在我的touchbegan方法实现longpressgesture。我正在使用NSTimer并在计数器变为3时记录计数器。我认识到这是长按。但是当我释放按钮然后再次按下mycounter时会保持之前的值并增加之前的值。虽然我将计数器分配给零。请帮助任何帮助。

 var counter : Int = 0
  var timer :NSTimer?

 override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

        timer = NSTimer()
        counter == 0;
        timer = NSTimer.scheduledTimerWithTimeInterval(1, target:self, selector: Selector("updateCounter"), userInfo: nil, repeats: true)

    }

    func updateCounter() {
       print(counter++)
        if (counter > 3){
            timer!.invalidate()
            timer = nil;
        }
    }
 override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {

        timer!.invalidate()
          timer = nil;
        counter == 0;

    }
  override public func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {



        if (counter>=3){
            print("hello")

        }

    }

1 个答案:

答案 0 :(得分:2)

经典等式==与分配=操作员混淆

timer = NSTimer() // this line is actually not needed
counter = 0

...

timer?.invalidate() // better use question mark to avoid a potential crash
timer = nil
counter = 0

并删除所有分号。