在 Xcode 中创建带有滑块的倒计时表

Creating a Countdown Watch with a slider in Xcode

大家好,我需要一些帮助。

我正在尝试创建一个可以从小时、分钟和秒开始倒计时的倒计时手表。现在我只能创建秒数倒计时,但我希望应用程序能够在我使用滑块 "slide" 时更新秒、分钟和小时。我发现很难正确更新标签并将 "hours and minutes" 添加到应用程序。有人可以帮我弄清楚逻辑吗?

这是我到目前为止编写的代码,它只需要几秒钟就可以正常工作。我还添加了一个音频文件,它会在最后播放,正如您在代码中看到的那样。

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
    }



}

这里是一种将秒数转换为格式化的小时、分钟、秒字符串的方法:

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

}

那么你可以这样使用它:

label.text = hmsFromSecondsFormatted(secondsCount)

多个 if 条件给你两件事:

  1. 单数/复数时间分量名称的结果(因此您得到“1 秒”而不是“1 秒”),并且

  2. returns只有必要的时间成分。因此,45 秒返回为“45 秒”而不是“0 小时 0 分钟 45 秒”

在您的实际应用中,您可能还会对时间组件名称使用本地化字符串。

希望对您有所帮助:)