You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将UIPickerView选中的时分秒值作为Timer倒计时的起始数值

解决方法

你只需要在触发计时器的fireTimer方法中,读取三个选择器当前选中的行,换算为总秒数赋值给counter即可,同时要注意避免重复创建计时器,建议提前销毁旧的计时器实例。

具体修改点:

  • 先销毁已存在的计时器,避免重复计时出现误差
  • 读取三个UIPickerView的选中行,对应转换为小时、分钟、秒的数值,按规则计算总秒数赋值给counter
  • 调整计时器间隔为1秒,符合正常倒计时的计时逻辑
  • 倒计时归0后自动销毁计时器,避免无效占用资源

修改后的核心代码

替换原有的fireTimer和timerAction方法即可:

@IBAction func fireTimer(_ sender: Any) {
    // 先销毁旧计时器,避免重复计时
    timer.invalidate()
    // 读取三个选择器的选中值,计算总秒数,数组索引和数值完全对应,直接用索引计算即可
    let selectedHour = hourPicker.selectedRow(inComponent: 0)
    let selectedMinute = minutePicker.selectedRow(inComponent: 0)
    let selectedSecond = secondPicker.selectedRow(inComponent: 0)
    counter = selectedHour * 3600 + selectedMinute * 60 + selectedSecond
    // 总秒数为0时不启动计时器
    guard counter > 0 else { return }
    // 初始化新计时器,间隔改为1秒
    timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.timerAction), userInfo: nil, repeats: true)
    // 立即刷新一次倒计时标签
    countDownLabel.text = "\(counter)"
}

@objc func timerAction() {
    if counter > 0 {
        counter -= 1
        countDownLabel.text = "\(counter)"
    } else {
        // 倒计时结束后销毁计时器
        timer.invalidate()
    }
}

内容的提问来源于stack exchange,提问作者zzzz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 17:54:02