How can I make a countdown with NSTimer?

后端 未结 15 1675
遇见更好的自我
遇见更好的自我 2020-11-30 03:17

How can I make a countdown with an NSTimer using Swift?

15条回答
  •  没有蜡笔的小新
    2020-11-30 03:34

    Make Countdown app Xcode 8.1, Swift 3

    import UIKit
    import Foundation
    
    class ViewController: UIViewController, UITextFieldDelegate {
    
        var timerCount = 0
        var timerRunning = false
    
        @IBOutlet weak var timerLabel: UILabel! //ADD Label
        @IBOutlet weak var textField: UITextField! //Add TextField /Enter any number to Countdown
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            //Reset
            timerLabel.text = ""
            if timerCount == 0 {
                timerRunning = false
            }
    }
    
           //Figure out Count method
        func Counting() {
            if timerCount > 0 {
            timerLabel.text = "\(timerCount)"
                timerCount -= 1
            } else {
                timerLabel.text = "GO!"
    
            }
    
        }
    
        //ADD Action Button
        @IBAction func startButton(sender: UIButton) {
    
            //Figure out timer
            if timerRunning == false {
             _ = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(ViewController.Counting), userInfo: nil, repeats: true)
                timerRunning = true
            }
    
            //unwrap textField and Display result
            if let countebleNumber = Int(textField.text!) {
                timerCount = countebleNumber
                textField.text = "" //Clean Up TextField
            } else {
                timerCount = 3 //Defoult Number to Countdown if TextField is nil
                textField.text = "" //Clean Up TextField
            }
    
        }
    
        //Dismiss keyboard
        func keyboardDismiss() {
            textField.resignFirstResponder()
        }
    
        //ADD Gesture Recignizer to Dismiss keyboard then view tapped
        @IBAction func viewTapped(_ sender: AnyObject) {
            keyboardDismiss()
        }
    
        //Dismiss keyboard using Return Key (Done) Button
        func textFieldShouldReturn(_ textField: UITextField) -> Bool {
            keyboardDismiss()
    
            return true
        }
    
    }
    

    https://github.com/nikae/CountDown-

提交回复
热议问题