How to add an action to a UIAlertView button using Swift iOS

后端 未结 8 1739
说谎
说谎 2020-12-12 22:13

I want to add another button other than the \"OK\" button which should just dismiss the alert. I want the other button to call a certain function.

var logInE         


        
8条回答
  •  失恋的感觉
    2020-12-12 22:58

    The Swifty way is to use the new UIAlertController and closures:

        // Create the alert controller
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)
    
        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }
    
        // Add the actions
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
    
        // Present the controller
        self.presentViewController(alertController, animated: true, completion: nil)
    

    Swift 3:

        // Create the alert controller
        let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)
    
        // Create the actions
        let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
            UIAlertAction in
            NSLog("OK Pressed")
        }
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
            UIAlertAction in
            NSLog("Cancel Pressed")
        }
    
        // Add the actions
        alertController.addAction(okAction)
        alertController.addAction(cancelAction)
    
        // Present the controller
        self.present(alertController, animated: true, completion: nil)
    

提交回复
热议问题