Swift 4 – 带有协议的自定义警报

Swift 4 – Custom Alerts with protocols

我在自定义警报和将操作发送回调用警报的 VC 方面遇到问题。

我有两个 classes:

我正在努力实现的用户旅程:

用户在 Factory class 完成后执行操作 我调用 ConfirmationAllert 使用这样的代码:

func showAlert() {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let myAlert = storyboard.instantiateViewController(withIdentifier: "ConfirmationAllert")
    myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
    (view as? UIViewController)?.present(myAlert, animated: true, completion: nil)
}

ConfirmationAllert class 我有按钮,其中:

第一个操作成功完成,第二个操作失败。我正在使用协议将第二个操作发送到 Factory VC,但有些东西不起作用,我不知道是什么。

这是我的代码:

工厂

final class FactoryViewController: UIViewController {
    let alert = ConfirmationAllert()

    @IBAction func didPressSave(_ sender: UIButton) {
        showAlert() 
    }

    func goToPreviousVc() {
        alert.delegate = self
        print("Inside factory") -> print don't get called
        // navigationController?.popViewController(animated: true) -> none of this works
        // dismiss(animated: true, completion: nil) -> none of this works
    }
}

extension FactoryViewController: ConfirmationAllertDelegate {
    func dismissVC() {
        goToPreviousVc()
        print("Go to previous")
    }
}

ConfirmationAllert

protocol ConfirmationAllertDelegate {
    func dismissVC()
}

class ConfirmationAllert: UIViewController {
    var delegate: ConfirmationAllertDelegate?

    @IBAction func didPressOk(_ sender: UIButton) { 
        self.delegate?.dismissVC() 
    }
}

我没有包括 viewDidLoad 方法,因为我没有在那里调用任何东西。

我的问题是方法 goToPreviousVc() 不执行任何操作。

预先感谢您的帮助!

我猜你的问题是你在 goToPreviousVc 设置了你的 ConfirmationAllertDelegate 应该使用那个委托调用。

相反,尝试在创建 myAlert 对象时设置委托

let myAlert = storyboard.instantiateViewController(withIdentifier: "ConfirmationAllert")
(myAlert as? ConfirmationAllert).delegate = self
// the rest of your code

之后,您的警报将在创建后有一个委托,当您按下按钮时,它应该会按预期工作。

尝试使用下面的代码

func showAlert() {
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    let myAlert = storyboard.instantiateViewController(withIdentifier: "ConfirmationAllert") as! ConfirmationAllert
    myAlert.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
    myAlert.modalTransitionStyle = UIModalTransitionStyle.crossDissolve
    myAlert.delegate = self
    present(myAlert, animated: true, completion: nil)
}