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

时间:2018-05-11 16:12:46

标签: ios swift4

这是之前的帖子。因为我是新人,所以我无法发表评论。

感谢Muhammad Zeeshan,他的aswer为我工作直到...

自最新的swift以来,代码发生了变化。现在单击取消按钮,在行中打开可选值时,意外发现错误为零

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")
        }
    }}

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

1 个答案:

答案 0 :(得分:0)

一旦我想出打开一个可选项就很容易了。

就在

之前
let alertController = presentedViewController as! UIAlertController

待办事项

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

我还要添加

timerCount = 5

showAlertView()

重置计数器。