简体   繁体   中英

cannot dismiss view controller via closure in UIAlert


All,

I am trying to write a method that will pass a closure to UIAlertAction such that when the OK button on an alert is tapped, both the alert and the calling view controller are dismissed.

What I have is:

func displayErrMsg( ecode : errorCodes ) ->() {

    var etitle = ""
    var etext  = ""
    var completionHandler: (()->())?
    switch ecode {
        case .NoError :
            etitle = "Found You!"
            etext  = "Check your email for a link to reset your password"
            completionHandler = { self.dismissViewControllerAnimated(true, { println("BUHBYE") })}
        case .EmailAddressNotFound :
             etitle = "Sorry, but we could not find you."
             etext  = "Have you registered?"
        case .MalFormedEmailAddress :
            etitle = "Opps!"
            etext   = "that is not a valid email address"
        default : println(" unrecognized error code: \(ecode)")
    }

    userMessage( self, etitle, etext, completionHandler )

}

which calls this:

public func userMessage(parent: UIViewController, title:String, message:String, completion:(() ->())?) {
    var okButton : UIAlertAction
    var alert    = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
    if let comp  = completion {
        okButton = UIAlertAction(title: "Ok", style: .Default, handler: { (alert) -> Void in
            comp()
        })
    }
    else
    {
        okButton = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, nil)
    }
    alert.addAction(okButton)
    parent.presentViewController(alert, animated: true, completion: nil)
}

In the scenario where the ecode is .NoError, I see the "BUHBYE" printed in the console, but the view is not removed after the OK button is tapped (the alert is removed). From what I know, the view controller that should be dismissed by the closure is the one from which the displayErrorMsg is called. Correct? Why doesn't this work?

Any and all help greatly appreciated. :bp:

I'm not familiar yet with swift, but if the logic is the same as Objective-C, you may want to present this view controller on the didDismiss alert view call, not the clickedButton :

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex

Also note that you can not remove a view controller presenting an alert view from the hierarchy until the alert view is actually dismissed.

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