不能通过UIAlert中的闭包来解除视图控制器

时间:2014-12-10 13:15:24

标签: ios swift closures viewcontroller


所有

我正在尝试编写一个方法,将一个闭包传递给UIAlertAction,这样当点击警报上的OK按钮时,警报和调用视图控制器都将被解除。

我拥有的是:

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 )

}

称之为:

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)
}

在ecode为.NoError的情况下,我看到" BUHBYE"打印在控制台上, 但点击确定按钮后,视图不会被删除(警报被删除)。据我所知,闭包应该关闭的视图控制器是displayErrorMsg 叫做。正确?为什么这不起作用?

任何和所有帮助都非常感谢。 :沸点:

1 个答案:

答案 0 :(得分:1)

我对swift不熟悉,但如果逻辑与Objective-C相同,您可能希望在 didDismiss 警报视图调用上显示此视图控制器,而不是 clickedButton

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

另请注意,在实际取消警报视图之前,您无法从层次结构中删除呈现警报视图的视图控制器。