【问题标题】:Refresh label every second每秒刷新标签
【发布时间】:2017-01-15 19:16:10
【问题描述】:

我尝试在 swift 3 中每秒刷新一个标签。 我总是收到以下错误:

Showing Recent Issues
Command failed due to signal: Segmentation fault: 11

这是我使用的代码:

    var TimerBeacon = Timer.scheduledTimer(timeInterval: 1, target: self, 
selector: Selector(("Timer")), userInfo: nil, repeats: true)


        func Timer() {
             //here is the label to refresh
         }

我希望有人可以帮助我:)

【问题讨论】:

  • 坏主意:Timer 是 Swift 3 中的保留字(结构)。重命名您的选择器至少以小写字母开头。
  • Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(yourMethodName), userInfo: nil, repeats: true) 使用上面的代码。 T\它将运行。请记住,您必须创建一个方法

标签: ios xcode swift3


【解决方案1】:

您的代码似乎没有针对 Swift 3 进行更新,并且可以使用一些更好的命名约定。

创建计时器:

let timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(update), userInfo: nil, repeats: true)

这是定时器每秒调用的函数:

func update() {
    // here is the label to refresh
}

当您想停止计时器时,请致电invalidate()

timer.invalidate()

【讨论】:

  • 还需要加上:timer.fire()
  • @BhavukJain 不,这不是真的。在Timer 上调用scheduledTimer 方法会自动启动计时器。我刚刚在一个新项目中验证了这一点。
  • @BhavukJain timer.fire() 不需要,除非选择器应该立即而不是在预定的时间间隔之后被调用。
【解决方案2】:

您可以在没有计时器的情况下实现相同的效果。使用以下代码

var iteration = 0
func updateLabel() {
    iteration = iteration == Int.max ? 0 : (iteration + 1)
        DispatchQueue.main.asyncAfter(deadline: .now() + 1, execute: {
            self.label.text = "\(self.iteration)"
            self.updateLabel()
        })

    }
}

请注意,我以iteration 为例。您可以按照自己的方式更新标签。

【讨论】:

    猜你喜欢
    • 2011-05-27
    • 1970-01-01
    • 2013-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-06
    • 2020-10-12
    相关资源
    最近更新 更多