【发布时间】:2016-11-16 18:48:25
【问题描述】:
为此寻求帮助,我有一个计时器,在提交密码后可以工作,这很棒,但是我需要在计时器启动后禁用按钮并禁用一段时间,(在代码中我已进入标称 90 秒)
但是按钮没有被禁用。
如果有人能告诉我哪里出错了,那就太棒了。
import UIKit
类 appiHour: UIViewController {
var timer = Timer()
var counter = 60
var password_Text: UITextField?
func enableButton() {
self.timerStartButton.isEnabled = true
}
@IBOutlet weak var timerLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func timerStartButton(_ sender: Any) {
var password_Text: UITextField?
let alertController = UIAlertController(title: "To start your own 2 Cocktails for £10 APPi Hour", message: "get a memeber of the team to enter the password, but use it wisely, as you can only use it once per day, with remember great power comes great responsability", preferredStyle: UIAlertControllerStyle.alert)
let tickoff_action = UIAlertAction(title: "let the APPiness commence", style: UIAlertActionStyle.default) {
action -> Void in
self.timerStartButton.isEnabled = false
Timer.scheduledTimer(timeInterval: 90, target: self, selector: #selector(appiHour.enableButton), userInfo: nil, repeats: false)
if let password = password_Text?.text{
print("password = \(password)")
if password == "baruba151" {
self.counter = 60
self.timerLabel.text = String(self.counter)
self.timer = Timer.scheduledTimer(timeInterval: 0.5, target: self, selector: #selector(appiHour.updateCounter), userInfo: nil, repeats: true)
}
} else {
print("No password entered")
}
}
alertController.addTextField { (txtpassword) -> Void in
password_Text = txtpassword
password_Text!.isSecureTextEntry = true
password_Text!.placeholder = ""
}
alertController.addAction(tickoff_action)
self.present(alertController, animated: true, completion: nil)
}
@IBOutlet weak var timerStartButton: UIButton!
func updateCounter() {
counter -= 1
timerLabel.text = String(counter)
if counter == 0{
timer.invalidate()
counter = 0
}
}
}
作为第二个问题,是否可以在应用程序处于后台时运行计时器?我知道苹果不赞成卫星导航、音乐应用等。但是有没有一种方法可以保持计时器并在本地发送通知让用户知道计时器已经结束?
提前致谢。
【问题讨论】:
-
我在任何地方的代码中都看不到“self.timerStartButton.isEnabled = false”。我怀疑这就是为什么您没有禁用按钮的原因。至于在后台运行计时器,是和否。您最多可以阻止 iOS 终止您的应用程序 3 分钟。查找“UIApplication.shared.beginBackgroundTask()”。但是,您将无法永远运行计时器。最终,iOS 会强制你的应用进入休眠状态。
-
由于我看不到您的 Interface Builder 布局,我假设您有两个动作连接到同一个按钮的 TouchUpInside 事件。 (Start_Button 和 timerStartButton)。这很好,但您需要确保两者都连接到您的按钮。右键单击您的按钮并确保您看到两者都正确连接。
-
是的,刚刚注意到,第二个操作不应该存在,因为只需要一个按钮操作,我已经按照应有的方式替换了代码,但是现在随着计时器的启动而崩溃验证后。 “self.timerStartButton.isEnabled = false”应该去哪里?
-
你有它的地方很好 - 只需按住 ctrl 单击你的按钮并将它拖到你的“timerStartButton”函数上。您需要使用拆分代码视图来执行此操作。这应该使得触摸按钮实际上会触发动作。
-
计时器并不是计算时间/秒的最准确方法。例如:developer.apple.com/library/content/documentation/Cocoa/… 即使一切运行并且用户没有退出应用程序,经过的总时间,在计时器触发 60 次后,可能会超过 60 秒。