简体   繁体   中英

UIAlertAction to pop to root view controller in Swift

I am using Swift programming language and using UIAlertController with "Cancel" button to display alert.
I'm using below code to create cancel button.

 let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: { (alert) -> Void in
    self.navigationController?.popToRootViewControllerAnimated(true)
 })

 alertController.addAction(cancelAction)

On tapping "Cancel" button, user has to be taken back to root view controller.
But the code is not compiling. The error its showing is as below:

Cannot invoke 'init' with an argument list of type `(title: StringLiteralConvertible, style: UIActionSheetStyle, handler: (($T2) -> Void) -> Void)`

I couldn't understand how to resolve this issue.

The other answer didn't work for me either; this one did. Add this function

func popToRoot() {
        self.navigationController?.popToRootViewControllerAnimated(true)
}

Then change the original function

{ (alert :UIAlertAction!) -> Void in
                self.popToRoot()
}

You could try this.

 let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: 
          { action in 
             self.navigationController?.popToRootViewController(animated: true)
          } )

尝试将(警报)替换为:

(alert :UIAlertAction!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM