Swift - How to present ViewController when tapping button in a custom AlertController

后端 未结 4 422
失恋的感觉
失恋的感觉 2021-01-28 03:31

I am developing in Swift 2.3

I have an Utils class enabling me to create UIAlertController easily.

public class Utils {

    cl         


        
4条回答
  •  北恋
    北恋 (楼主)
    2021-01-28 03:40

    I would suggest using segue identifiers as the passed parameter (make sure you reference a segue that starts in the ViewController you call the "buildAlert" function from).

    public class Utils {
    
    class func buildAlertInfo(withTitle title: String?, andMessage message: String?, withSegue segueIdentifier: String?, sender: Any?) -> UIAlertController {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
        alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: handler: {
                    action in
                    self.performSegue(withIdentifier: segueIdentifier, sender: sender)
                })
    
        return alertController
    }
    

    This can also be achieved without creating a new function, just sending the handler part from above as a parameter to the function you already have, like this:

    let alert = Utils.buildAlertInfo(withTitle: "Information", andMessage: "John Snow is dying", withHandler: {
                    action in
                    self.performSegue(withIdentifier: "mySegueIdentifier", sender: self)
                })
    

    EDIT: Note that the sender part can be any object that has an @IBOutlet reference in the ViewController the function call takes place

提交回复
热议问题