【发布时间】:2021-09-10 06:30:13
【问题描述】:
我正在努力完成这项工作。我想要一个按钮,一旦按下一定时间就会被禁用。一旦该时间结束,该按钮将再次启用,直到再次按下它,然后在设定的时间内禁用它。我不希望通过重新启动应用程序轻松再次启用该按钮。它必须保持禁用状态,直到时间结束,而不是直到应用程序的下一次启动.. 到目前为止,我的代码只能禁用按钮一次。它不起作用,在时间过去后再次启用它。在我重新启动应用程序后,该按钮也再次启用。这是不应该发生的。
任何人有一个想法,我怎样才能让它按照我想要的方式工作?
这是我的代码:
button.isUserInteractionEnabled = false
Timer.scheduledTimer(withTimeInterval: 5, repeats: true, block: { _ in
button.isUserInteractionEnabled = false
})
我也试过这样:
_ = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)
_ = Timer.scheduledTimer(timeInterval: 0.0, target: self, selector: #selector(fireTimer2), userInfo: nil, repeats: false)
@objc 是:
@objc func fireTimer() {
print("Timer fired!")
}
@objc func fireTimer2() {
print("Start timer.")
}
我想尝试一下,如果我可以设置开始时间和重复时间,希望通过按钮让事情顺利进行。我没有。 谁能帮帮我?
非常感谢!万事如意
更新,6 月 29 日:
这是代码,我用于我的按钮并使我想要的禁用/启用功能起作用。
@objc private let actionButton: UIButton = {
let button = UIButton()
button.setTitle("Button Title", for: .normal)
button.titleLabel?.font = UIFont(name: "Times New Roman", size: 16)
button.setTitleColor(.secondaryLabel, for: .normal)
button.addTarget(self, action: #selector(didTapButton), for: .touchDown)
return button
}()
@objc func didTapButton() {
self.actionButton.isUserInteractionEnabled = false
Timer.scheduledTimer(withTimeInterval: 20, repeats: true) { _ in
self.actionButton.isUserInteractionEnabled = true
}}
那么如何将计时器中的数据存储在core data(???) 或UserDefaults(???) 或其他任何地方,以便在重新启动应用程序时计时器不会重置?
【问题讨论】:
-
您是否尝试向
UserDefaults添加时间,您的计时器/初始化方法可以检查“nextAvailableTime”变量 -
使用大调度。