使用回调来重现UIAlertViewController

时间:2016-09-05 23:22:53

标签: ios swift callback

我想重现UIAlertController的功能,因为类不是很容易定制的。所以这就是我所做的:

  1. 创建一个DeleteDeckViewController,只有两个按钮是,否,带回调方法

    class DeleteDeckViewController: UIViewController {
    
        var deleteDeck : ((deleteDeck : Bool) -> ())?
    
        @IBAction func yesButton(sender: AnyObject) {
            deleteDeck!(deleteDeck: true)
        }
    
        @IBAction func noButton(sender: AnyObject) {
            deleteDeck!(deleteDeck: false)
        }
    }
    
  2. 在主视图控制器中按下删除按钮时,会创建一个弹出的DeleteDeck

    func handleDelete(detailDeckView: DetailDeckView) {
    
        let deleteDeckViewController = DeleteDeckViewController(nibName: "DeleteDeckViewController", bundle: nil)
        let popup = PopupDialog(viewController: deleteDeckViewController, transitionStyle: .BounceDown, buttonAlignment: .Horizontal, gestureDismissal: true)
        presentViewController(popup, animated: true, completion: nil)
    
        deleteDeckViewController.deleteDeck(true) { () -> Void in
            print("Deck deleted")
        }
    }
    
  3. 我想要做的是使用回调来告诉我的主视图控制器用户是否按下了是,然后根据是或否进行一些操作。虽然,我不知道正确的方法。我已经阅读了一些关于回调的文章,但我不知道在这种情况下如何应用它。我尝试使用委托只是我需要传递DetailDeckView对象而不使用它,这就是为什么我认为回调将是一个更好的选择。

    有人能指出我正确的方向吗?

1 个答案:

答案 0 :(得分:1)

DeleteDeckViewController中,您已将deleteDeck变量声明为函数。因此,当您使用此类的实例时,需要将其设置为变量。因此,您的代码看起来更像下面的内容(未经测试):

func handleDelete(detailDeckView: DetailDeckView) {

    let deleteDeckViewController = DeleteDeckViewController(nibName: "DeleteDeckViewController", bundle: nil)
    deleteDeckViewController.deleteDeck = myDeleteHandler
    let popup = PopupDialog(viewController: deleteDeckViewController, transitionStyle: .BounceDown, buttonAlignment: .Horizontal, gestureDismissal: true)
    presentViewController(popup, animated: true, completion: nil)
}

func myDeleteHandler(shouldDelete: Bool) {
    if shouldDelete {
        print("Delete deck")
    }
}

此外,在您的代码中,如果deleteDeck!为零,则不会使用会失败的deleteDeck,最好使用以下代码:

if let deleteDeck = self.deleteDeck {
    deleteDeck(true)
}

这将创建一个名为deleteDeck的本地非可选变量,可以保证不包含nil。

您可以将此代码构建到DeleteDeckViewController以进一步简化:

class DeleteDeckViewController: ....

    func showDialog(vc: UIViewController, completion: ((deleteDeck : Bool) -> Void)?) {
        self.deleteDeck = completion
        let popup = PopupDialog(viewController: vc, transitionStyle: .BounceDown, buttonAlignment: .Horizontal, gestureDismissal: true)
        presentViewController(popup, animated: true, completion: nil)
    }