【问题标题】:Int value PersistInt 值持久化
【发布时间】:2016-04-21 08:17:11
【问题描述】:

当我的 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")

        }

    }

【问题讨论】:

  • 你为什么决定不使用UILongPressGestureRecognizer
  • 因为没有调用长按手势选择器

标签: iphone swift swift2 nstimer ios9.2


【解决方案1】:

这是 == 与 assign = 运算符混淆的经典等式

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

并删除所有分号。

【讨论】:

    猜你喜欢
    • 2011-11-20
    • 1970-01-01
    • 1970-01-01
    • 2020-12-05
    • 2011-06-11
    • 2021-05-16
    • 2011-11-10
    • 2015-02-27
    • 1970-01-01
    相关资源
    最近更新 更多