3004

Creating a Countdown Watch with a slider in Xcode

Hello guys i need some help.

Im trying to create a countdown watch which can count down from hours, minuts and seconds. Right now im only able to create the countdown for seconds but i want the application to be able to update the seconds, minutes and hours when i "slide" with the slider. I find it very hard to update the label correctly and add "hours and minutes" to the application. Can someone please help me figuring the logic out.

This is the code i have written so far and it works fine only with seconds.. I also added a audio file which will play in the end as you can see in the code.

class ViewController: UIViewController { var secondsCount = 30; var timer = Timer() var audioPlayer = AVAudioPlayer() @IBOutlet weak var label: UILabel! @IBOutlet weak var labelmin: UILabel! // Slideren som slider tid for sal 1 @IBOutlet weak var sliderOutlet: UISlider! @IBAction func slider(_ sender: UISlider) { //Live changes the numbers secondsCount = Int(sender.value) label.text = String(secondsCount) + " Seconds" } //Start button @IBOutlet weak var startOutlet: UIButton! @IBAction func start(_ sender: Any) { //Nederstående kode aktiverer funktionen counter() timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(ViewController.counter), userInfo: nil, repeats: true) sliderOutlet.isHidden = true startOutlet.isHidden = true } //Counter function func counter() { secondsCount -= 1 label.text = String(secondsCount) + " Seconds" if (secondsCount == 0) { timer.invalidate() audioPlayer.play() } } //Stop button @IBOutlet weak var stopOutlet: UIButton! @IBAction func stop(_ sender: Any) { timer.invalidate() secondsCount = 30 sliderOutlet.setValue(30, animated: true) label.text = "30 Seconds" audioPlayer.stop() sliderOutlet.isHidden = false startOutlet.isHidden = false } // viewDidLoad override func viewDidLoad() { super.viewDidLoad() do { let audioPath = Bundle.main.path(forResource: "1", ofType: ".mp3") try audioPlayer = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!)) } catch { //ERROR } }

Answer1:

Here is one way to convert number of seconds into a formatted hours, minutes, seconds string:

func hmsFromSecondsFormatted(seconds: Int) -> String { let h = seconds / 3600 let m = (seconds % 3600) / 60 let s = seconds % 60 var newText = "" if h > 0 { newText += "\(h)" if h == 1 { newText += " hour, " } else { newText += " hours, " } } if m > 0 || h > 0 { newText += "\(m)" if m == 1 { newText += " minute, " } else { newText += " minutes, " } } newText += "\(s)" if s == 1 { newText += " second" } else { newText += " seconds" } return newText }

Then you could use it like this:

label.text = hmsFromSecondsFormatted(secondsCount)

The multiple if conditions give you two things:

<ol> <li>

a result of singular / plural time component names (so you get "1 second" instead of "1 seconds"), and

</li> <li>

returns only the necessary time components. So, 45 seconds is returned as "45 seconds" instead of "0 hours, 0 minutes, 45 seconds"

</li> </ol>

In your actual app, you probably will also use localized strings for the time component names.

Hope that helps :)

Recommend

  • Which MySQL collation compares e.g. é and e as equal?
  • Unable to Decrease CIVignette effect using UISlider
  • Inconsistent datatypes: expected REF got .. error when trying to insert data
  • Numpy - Finding matches across multiple co-ordinates
  • swift accessing variable from another file
  • Generate source using jaxb from an xsd that is in my classpath
  • import XML to HTML
  • Pick folder routine going to Error handler - Excel VBA
  • getting cpu usage of one process using c++ (win32)
  • tableView.reloadData() Table not updating
  • How to do a 30 minute count down timer
  • Android google maps v2 execute asynctask when user stops moving the camera
  • How to play a BGM and know current playback time on in cocos2d ios?
  • Rx grouped throttling
  • proto2 with Spark cannot run
  • How to remove zoom slider in UIImagePickerController
  • C# Download Speed Asynchronously
  • Moving a camera
  • Blink image with JQuery
  • Javascript's SetTimeout, SetInterval and ClearInterval equivalent in c#
  • Animation: Timer vs Idle
  • How to call java class from oracle trigger?
  • Task getting rejected although threads are available
  • d3 animated line graph
  • Swift Progress View with NSTimer
  • AS3 String Memory Leak
  • Drupal: Hierarchical taxonomical breadcrumb trail
  • Programmatically change first page jQuery Mobile shows
  • How do js animations work?
  • PHP curl_multi_exec output to array
  • SharePoint timer job add list items, but does not trigger the associated workflow
  • How to Update UILabel from Another ViewController
  • EJB @Schedule issue
  • Printing input from TextField to a Label in Xcode with Swift
  • powershell: script to start a program with parameters?
  • NSTimer and updating UI
  • GDB skips over my code!
  • Get UILabel out of UIButton
  • Receive mouse move even cursor is outside control
  • Faster Way To Simultaneously Iterate Over Rolling Window Of Two Or More Numpy Arrays?