倒数计时器显示在UIAlertController中的按钮内部,然后启用按钮快速更新



这是上一篇文章。 因为我是新人,所以我不能发表评论。

感谢穆罕默德·齐山,因为他的助手为我工作,直到......

自从最新的 swift 以来,代码发生了变化。 现在,您单击取消按钮并收到错误 意外发现 nil 时,在行上解开可选值

let alertController = presentedViewController as! UIAlertController

实际更新的代码

var timer = Timer()
var timerCount: Int = 5

class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func okButton(_ sender: Any) {
showAlertView()
}
func showAlertView() {
let alertController = UIAlertController(title: "Title", message: "Message of alert", preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .default, handler: nil)
okAction.isEnabled = false
alertController.addAction(okAction)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
present(alertController, animated: true) {
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.countDownTimer), userInfo: nil, repeats: true)
}
}
@objc func countDownTimer() {
timerCount -= 1
let alertController = presentedViewController as! UIAlertController
let okAction = alertController.actions.first
if timerCount == 0 {
timer.invalidate()
okAction?.setValue("Ok", forKey: "title")
okAction?.isEnabled = true
} else {
okAction?.setValue("Ok (timerCount)", forKey: "title")
}
}}

所以我想知道如何在没有错误的情况下杀死它。

一旦我想出解开一个可选包,就很容易了。

就在之前

let alertController = presentedViewController as! UIAlertController

if presentedViewController == nil {
timer.invalidate()
return
}

我还必须添加

timerCount = 5

以前

showAlertView()

重置计数器。

相关内容

最新更新