gpt4 book ai didi

ios - 使用回调重现 UIAlertViewController

转载 作者:行者123 更新时间:2023-11-28 16:13:17 26 4
gpt4 key购买 nike

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

  1. 创建一个只有两个按钮 Yes 和 No 的 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. 在主视图 Controller 中,当按下删除按钮时,它会创建一个弹出 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")
    }
    }

我想做的是使用回调告诉我的主视图 Controller 用户是否按下了是或否,然后根据是或否执行一些操作。虽然,我不知道正确的方法。我读过几篇关于回调的文章,但我不知道如何在这种情况下应用它。我试过使用委托(delegate),只是我需要在不使用它的情况下传递 DetailDeckView 对象,所以这就是为什么我认为回调是更好的选择。

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

最佳答案

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 为 nil 将会失败,最好使用如下代码:

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

关于ios - 使用回调重现 UIAlertViewController,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39338724/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com