8

在我正在进行的一个项目中,我必须编写一个 UIAlert 帮助模块,它会在我的 iOS 应用程序中到处显示弹出窗口。弹出窗口被编写为类函数,我可以在代码中的任何位置简单地调用它们(类是静态的,所有函数也是如此)。

我现在遇到一个非常奇怪的错误,如果您关闭警报一次,然后再次打开它,它的操作不再起作用(例如,不调用操作处理程序)。如果您在第一次显示弹出窗口时单击该操作,它确实有效,但是......

这是发生此错误的特定弹出窗口的代码(不影响其他弹出窗口):

static func popSkipWalkthrough() {
    let alert = UIAlertController(title: "Skip", message: "whatever", preferredStyle: .Alert)

    alert.addAction(cancelAction)
    alert.addAction(skipWalkthroughAction)
    appDelegate.window!.rootViewController!.presentViewController(alert, animated: true, completion: nil)
}

skipWalkthroughAction定义如下:

static let skipWalkthroughAction = UIAlertAction(title: "Continue", style: .Default, handler: { (action: UIAlertAction!) -> Void in
    appDelegate.setWindowViewTo("NavCtrl", navigateTo: false)
    CallIn.Settings.didWalkthrough = true
})

并且cancelAction定义为:

static let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)

每次您在演练的最后一步中按下“跳过”按钮时,都会特别显示此弹出窗口...

我已经尝试了一些关于导致这种行为的原因的线索,我认为这可能与弹出窗口没有真正被释放有关,但我现在完全不确定......

有任何想法吗 ?

4

1 回答 1

5

尽管我对这个可重用部分的编码方式有疑问,但这个问题可以通过发送copy:消息来解决skipWalkthroughAction。只需执行以下操作:

static func popSkipWalkthrough() {
    let alert = UIAlertController(title: "Skip", message: "whatever", preferredStyle: .Alert)

    alert.addAction(cancelAction.copy() as! UIAlertAction)
    alert.addAction(skipWalkthroughAction.copy() as! UIAlertAction)
    appDelegate.window!.rootViewController!.presentViewController(alert, animated: true, completion: nil)
}

这应该解决它。

您也可以通过移动alert到实例级别来解决此问题。那你就不用寄了copy:

更好的方法

如果您想要“真正的”可重用体验UIAlertController,最好创建一个UIViewController扩展。我的一个项目中有这个:

extension UIViewController {
    func showAlertControllerWithTitle(title:String?,message:String?,actions:[UIAlertAction],dismissingActionTitle:String?, dismissBlock:(() -> ())?) -> UIAlertController {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        if dismissingActionTitle != nil {
            let okAction = UIAlertAction(title: dismissingActionTitle, style: .Default) { (action) -> Void in
                dismissBlock?()
                alertController.dismissViewControllerAnimated(true, completion:nil)
            }
            alertController.addAction(okAction)
        }
        for action in actions {
            alertController.addAction(action)
        }
        self.presentViewController(alertController, animated: true, completion:nil)
        return alertController
    }
}
于 2016-02-09T12:15:46.410 回答