Home>

I want to make the time elapse every second like a digital clock
I don't know what code to write.
I'd be happy if you could tell me more about Swift.

The current code looks like this

import UIKit

class ViewController: UIViewController {

var nowTime: UILabel = UILabel ()
var screenWidth: CGFloat = 0.0
var screenHeight: CGFloat = 0.0

override func viewDidLoad () {
super.viewDidLoad ()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor.white // Set the view screen background to white

screenWidth = self.view.bounds.width // Get the horizontal width of the screen
screenHeight = self.view.bounds.height // Get the height of the screen

// UILabel frame settings
nowTime = UILabel (frame: CGRect (x: screenWidth/2-100,
y: screenHeight/2,
width: screenWidth/2,
height: screenHeight/6))

let now = NSDate () // NSDate class instance creation

let formatter = DateFormatter () // Create an instance of DateFormatter class
formatter.locale = Locale (identifier:"en_US")
formatter.dateFormat ="HH: mm: ss"
nowTime.text = formatter.string (from: now as Date)

nowTime.textAlignment = .center
nowTime.textColor = UIColor.black

self.view.addSubview (nowTime)
}

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

}

Current time is only displayed once so no time has passed.

I tried to get the time using a while statement but it didn't start

  • Answer # 1

    viewDidLoad () is only called once after the ViewController view is created.
    The label nowTime can be created with viewDidLoad (),
    nowTime.text must be changed at regular intervals.

    let formatter = DateFormatter () // Generate an instance of DateFormatter class
    formatter.locale = Locale (identifier: "ja_JP")
    formatter.dateFormat = "HH: mm: ss"
    nowTime.text = formatter.string (from: now as Date)

    Make this part a separate method and call it at regular intervals.

    For example, you can find various periodic processes by searching for "swift fixed time".