Michael
Michael

Reputation: 303

How to count with a label in Swift2

I have 1 Button and 1 Label. When I tap the Button, the label should count to the number end. Now it shows immediately the end result. How can I make it so that every number between is also shown? Is there existing a function for doing that (start and count to a number with special effects)?

Thanks

var start = 0
var end = 10
@IBAction func Button1(sender: UIButton) {
    while start <= end {
        Label1.text = "\(start)"
        start = start + 1
    }

Upvotes: 1

Views: 1459

Answers (1)

Mudith Chathuranga Silva
Mudith Chathuranga Silva

Reputation: 7444

Use this one ,

import UIKit

class ViewController: UIViewController {

var start = 0
var end = 10

var timer = NSTimer()

func updateTime() {

    if start == end {

    timer.invalidate()

    } else {


        start++

        Label1.text = "\(start)"
    }




}

@IBOutlet weak var Label1: UILabel!

@IBAction func button(sender: AnyObject) {


        timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: Selector("updateTime"), userInfo: nil, repeats: true)
}



override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


}

You can change the fast by changing NSTimer interval currently set to 0.5 , set what ever you want

Upvotes: 1

Related Questions