Swift alert view with OK and Cancel: which button tapped?

前端 未结 6 787
耶瑟儿~
耶瑟儿~ 2021-01-30 01:16

I have an alert view in Xcode written in Swift and I\'d like to determine which button the user selected (it is a confirmation dialog) to do nothing or to execute something.

6条回答
  •  长情又很酷
    2021-01-30 01:46

    Updated for swift 3:

    // function defination:

    @IBAction func showAlertDialog(_ sender: UIButton) {
            // Declare Alert
            let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to Logout?", preferredStyle: .alert)
    
            // Create OK button with action handler
            let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
                 print("Ok button click...")
                 self.logoutFun()
            })
    
            // Create Cancel button with action handlder
            let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
                print("Cancel button click...")
            }
    
            //Add OK and Cancel button to dialog message
            dialogMessage.addAction(ok)
            dialogMessage.addAction(cancel)
    
            // Present dialog message to user
            self.present(dialogMessage, animated: true, completion: nil)
        }
    

    // logoutFun() function definaiton :

    func logoutFun()
    {
        print("Logout Successfully...!")
    }
    

提交回复
热议问题