RubberDucky4444 RubberDucky4444 - 8 months ago 36
Swift Question

Countdown timer shown inside of button in UIAlertController then enable button swift

Is it possible to create a UIAlertController that has a button that is initially disabled and has a 5 then 4 then 3..2..1 then enabled.

I want the user to actually read the message inside the controller and i figure that will be annoying enough to actually stop them from mindlessly tapping OK

If its possible how would I start going about doing this?



Its little hacky as we are trying to modify the read only property of UIAlertAction. However it works fine for me. Alternatively you can create your custom view controller that looks like UIAlertController:

var timer: NSTimer?
var timerCount: Int = 5    
func showAlertView() {
            let alertController = UIAlertController(title: "Title", message: "Message of alert", preferredStyle: .Alert)

            let okAction = UIAlertAction(title: "Ok", style: .Default, handler: nil)
            okAction.enabled = false

            alertController.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
            presentViewController(alertController, animated: true) {
                self.timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(self.countDownTimer), userInfo: nil, repeats: true)

        func countDownTimer() {
            timerCount -= 1

            let alertController = presentedViewController as! UIAlertController
            let okAction = alertController.actions.first

            if timerCount == 0 {
                timer = nil

                okAction?.setValue("Ok", forKey: "title")
                okAction?.enabled = true
            } else {
                okAction?.setValue("Ok \(timerCount)", forKey: "title")

This is how it looks like:

enter image description here