单击任何按钮启动计时器

时间:2016-01-06 19:14:55

标签: swift timer

var nsTimer = NSTimer()

override func viewDidLoad() {

    super.viewDidLoad()



    // Do any additional setup after loading the view.
}

override func viewDidDisappear(animated: Bool) {
    self.nsTimer.invalidate()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
     nsTimer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("updatetime"), userInfo: nil, repeats: true);
}

func updateTime() {
    counter = counter + 0.1
    timer.text = String(format: "%.1f", counter) + "s"
}

任何人都知道吗? 当我点击任何按钮计时器开始,当我点击另一个按钮计时器包含

3 个答案:

答案 0 :(得分:0)

您的计时器正在启动,因为您从touchesBegan触发事件,如果视图上有任何触摸,它将启动。 如果你想从一个uibutton启动计时器,我建议你从一个与a按钮关联的@IBAction触发计时器。现在,如果你坚持将计时器保持在touchesBegan中,你需要一些逻辑,所以启动触发计时器而不是在视图中的每次触摸时触发计时器

答案 1 :(得分:0)

您必须创建一个IBAction并将所有按钮链接到它。

@IBAction func buttonTapped(sender: AnyObject) {
//this will check if your timer is running if not the start the timer, if the timer is already running do nothing and keep timer running 
 if !nsTimer.Enabled {
   nsTimer.Start()
   } 
 }

确保将所有按钮连接到此方法,并从touchesBegan

中删除您的代码

答案 2 :(得分:0)

您必须创建一个IBAction并将所有按钮链接到它。

@IBAction func buttontapped(sender:AnyObject){         if!nsTimer.valid {检查计时器是否启动         nsTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,target:self,selector:Selector(&#34; updateTime&#34;),userInfo:nil,repeats:true);         }

确保将所有按钮连接到此方法,并从touchesBegan

中删除您的代码