ios - Creating a Countdown Timer in Swift -
i have wrote code counts down specific date.
how make each element of countdown shown in separate label.
so have label shows number of days, label show number of hours, label show number of minutes , label show number of seconds.
code:
class viewcontroller: uiviewcontroller { @iboutlet weak var datelabeloutlet: uilabel! let currentdate = date() let dateformatter = dateformatter() let usercalendar = calendar.current let requestedcomponent: set<calendar.component> = [.day,.hour,.minute,.second] override func viewdidload() { super.viewdidload() // additional setup after loading view, typically nib. let timer = timer.scheduledtimer(timeinterval: 1.0, target: self, selector: #selector(printtime), userinfo: nil, repeats: true) timer.fire() } func printtime() { dateformatter.dateformat = "dd/mm/yy hh:mm:ss" let starttime = date() let endtime = dateformatter.date(from: "25/12/16 00:00:00") let timedifference = usercalendar.datecomponents(requestedcomponent, from: starttime, to: endtime!) datelabeloutlet.text = "\(timedifference.day!) days \(timedifference.hour!) hours \(timedifference.minute!) minutes \(timedifference.second!) seconds" } override func didreceivememorywarning() { super.didreceivememorywarning() // dispose of resources can recreated. }
}
your code calculates difference in datecomponents
, , builds string day, hour, minute , second differences combined.
just change line:
datelabeloutlet.text = "\(timedifference.day!) days \(timedifference.hour!) hours \(timedifference.minute!) minutes \(timedifference.second!) seconds"
you'll need create 4 labels , put timedifference.day
in one, timedifference.hour
in another, timedifference.minute
in third, , timedifference.second
in 4th label.
if wrote code think obvious - or else's code copy/pasted?
Comments
Post a Comment