iphone - Int 值持久化

标签 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")

        }

    }

最佳答案

这就是经典等式 == 与赋值 = 运算符的混淆

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

并删除所有分号。

关于iphone - Int 值持久化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763733/

相关文章:

ios - 如何在锁定屏幕上添加备注/提醒

iphone - For循环产生 "unrecognized selector sent to instance"错误

iphone - UITextField 不会在整个项目中自动大写

swift - 如何删除此 EXC_BAD 访问错误?

objective-c - OS X 在后台打开 URL 方案

arrays - .sort 在 Swift 2.0 中不起作用

iphone - 如何允许一个线程改变数组属性,而另一个线程迭代数组的副本

iphone - TabBarController 委托(delegate)不工作

swift - 在 Swift 中刷新后刷新控件不会向上滑动屏幕

ios - 什么是 CGFloat.random(min : CGFloat, max : CGFloat) of swift 2 in swift 3?