• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

ios - 创建一个每秒运行的计时器,在第二个?

[复制链接]
菜鸟教程小白 发表于 2022-12-11 19:08:03 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我有一个特定日期的倒计时。它看起来很不错,并且每秒更新一次以显示倒计时。这是我用来创建计时器的代码:

func scheduleTimeLabelsUpdateTimer() {

    var components = Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date())
    components.second! += 1

    let nextSecondDate = Calendar.current.date(from: components)!

    let timer = Timer(fireAt: nextSecondDate, interval: 1, target: self, selector: #selector(updateTimeLabels), userInfo: nil, repeats: true)

    RunLoop.main.add(timer, forMode: .commonModes)

}

但是,我希望它每秒更新一次,第二次,以便时钟在每一秒过去的同时更新。现在它从调用此方法开始每秒更新一次,该方法位于 viewDidLoad() 中。

例如,如果倒计时设置为午夜,我希望它在午夜准确地达到零。现在,它可能会在午夜后略微达到零,具体取决于用户打开此屏幕时的秒数。

编辑:这是向用户显示倒计时的方式。 updateTimeLabels() 只是根据距该日期的剩余时间设置每个标签的文本。我希望每个标签都能准确地每秒更新一次。这样倒计时将准确地按时“归零”。请注意,现在,秒数达到零,然后状态栏上的系统时钟更新。我希望这些同时发生。

enter image description here

这段代码是我几个月前在 Stack Overflow 上找到的,在 updateTimeLabels() 中调用它来计算剩余时间:

public func timeOffset(from date: Date) -> (days: Int, hours: Int, minutes: Int, seconds: Int) {
    // Number of seconds between times
    var delta = Double(self.seconds(from: date))

    // Calculate and subtract whole days
    let days = floor(delta / 86400)
    delta -= days * 86400

    // Caluclate and subtract whole hours
    let hours = floor(delta / 3600).truncatingRemainder(dividingBy: 24)
    delta -= hours * 3600

    // Calculate and subtract whole minutes
    let minutes = floor(delta / 60.0).truncatingRemainder(dividingBy: 60)
    delta -= minutes * 60

    // What's left is seconds
    let seconds = delta.truncatingRemainder(dividingBy: 60)

    return (Int(days), Int(hours), Int(minutes), Int(seconds))
}



Best Answer-推荐答案


在您的代码中,您在初始化组件时从不使用纳秒

因此计时器将始终按到第二个轮数。

我在下面测试您的代码,在选择器 enter image description here 中打印 Date()

我不确定这是否是您所说的“命中零”,希望这会有所帮助

关于ios - 创建一个每秒运行的计时器,在第二个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42547362/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap