Search code examples
swift3timestampuislider

Converting Int to minutes & display in text box swift 3


I am currently learning Swift. I have added a UISlider that controls the number within a text box (where I am displaying an int).

I have found a function to convert the input into hours/minutes/seconds but I am still trying to work out how to call this conversion function then update the value within the text box.

To convert to Hours/Minutes/Seconds

//Define

func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int){
    return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}

//Use
secondsToHoursMinutesSeconds(27005)
(7,30,5)

The current UI Slider

@IBAction func valueSelection(_ sender: UISlider) {   
    timeAmount.text = String(Int(sender.value))     
}

Solution

  • You just have to call secondsToHoursMinutesSeconds inside valueSelection and format the returned tuple into a string of your desired format. I just formatted the time like "hours:minutes:seconds" as an example, you can change it to your desired format.

    @IBAction func valueSelection(_ sender: UISlider) {
        let time = secondsToHoursMinutesSeconds(Int(sender.value))
        timeAmount.text ="\(time.0):\(time.1):\(time.2)"
    }