Reputation: 23
This is my code.
//
// ViewController.swift
// Stopwatch
//
// Created by Orkun Atasoy on 12.09.15.
// Copyright (c) 2015 Orkun Atasoy. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var timerButton: UIButton!
var timer : NSTimer?
var ms = 0
@IBAction func buttonTapped(sender: AnyObject) {
timerButton.setTitle("Stopp", forState:UIControlState.Normal)
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update() {
self.ms++
timerLabel.text = String(self.ms)enter code here
}
}
The Problem is when i run the build it comes the introscreen with big text "Stopwatch" and the it is like freezed there. But it should come a label with button downside which has a text "start". When i click the button it should start counting and the label should change to "stopp". When i click again the it should stop the timer.
I dont get what the Problem ist. I am a Swift newbie. I would be pleased if you could help me.
Thank you for your attention
EDIT >> the label text is at the beginning "00:00".
Upvotes: 1
Views: 294
Reputation: 71854
Looks like you are messing with IBOutlet
connections and I have corrected some of your code and here is working code:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var timerLabel: UILabel!
@IBOutlet weak var timerButton: UIButton!
var timer : NSTimer?
var ms = 0
override func viewDidLoad() {
timerLabel.text = "00:00"
}
@IBAction func buttonTapped(sender: AnyObject) {
if timerButton.currentTitle == "Stopp" {
timer?.invalidate()
timerButton.setTitle("Start", forState:UIControlState.Normal)
} else {
timerButton.setTitle("Stopp", forState:UIControlState.Normal)
self.timer = NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
}
func update() {
self.ms++
timerLabel.text = String(self.ms)
}
}
And First of all remove all outlets from your storyboard view controller and connect it this way:
And if you want check THIS sample project.
Upvotes: 1
Reputation: 150615
The method you call when the timer fires is incorrect. From the documentation:
The selector should have the following signature: timerFireMethod: (including a colon to indicate that the method takes an argument). The timer passes itself as the argument, thus the method would adopt the following pattern: - (void)timerFireMethod:(NSTimer *)timer
So your method should be:
func update(timer: NSTimer) {
self.ms++
timerLabel.text = String(self.ms)
}
And you should set up your timer as:
NSTimer.scheduledTimerWithTimeInterval(0.01, target: self, selector: "update:", userInfo: nil, repeats: true)
There are a few more things I could mention - such as no need to use self
when unambigously using variables, and using a dispatch timer instead of an NSTimer, but this should at least solve your immediate problem.
Upvotes: 0