nil 在两个 ViewController 和两个不同的 Bundle (swift) 之间进行委托

nil Delegate between two ViewController with two different Bundle (swift)

nil 在两个 ViewController 与两个不同的 Bundle 之间使用 swift 进行委托 4(在第二个代码中注释)

这是我的代码:

第一个 ViewController :

class FirstVC : UIViewController, MerchantResultObserver{
    var secVC = SecondVC()

  override func viewDidLoad() {
        secVC.delegate = self

            let storyboard = UIStoryboard(name: “SecondVC”, bundle: Bundle(identifier: “SecondBundle”))
            let controller = storyboard.instantiateInitialViewController()
            self.present(controller!, animated: true, completion: nil)

            secVC.initSecondVC(data)
    }



 func Error(data: String) {
        print("-------------Error Returned------------- \(data)")
    }


 func Response(data: String) {
        print("-------------Response Returned------------- \(data)")
    }

}

第二个ViewController:

public class SecondVC: UIViewController {
    public weak var delegate: MerchantResultObserver!


 public func initSecondVC(_ data : String){
        print(data)
}

@IBAction func sendRequest(_ sender: UIButton) {
            delegate?.Response(data: “dataReturnedSuccessfully”)  // delegate is nil //
           dismiss(animated: true, completion: nil)                 // returned to FirstVC without returning “dataReturnedSuccessfully” //
}

}

public protocol MerchantResultObserver: class{
    func Response(data : String)
    func Error(data : String)
}

如有任何帮助,我们将不胜感激

var secVC = SecondVC()

let storyboard = UIStoryboard(name: “SecondVC”, bundle: Bundle(identifier: “SecondBundle”))
let controller = storyboard.instantiateInitialViewController() as? SecondVC

这两个是不同的实例。

你可以给控制器分配一个委托,比如

controller.delegate = self

它将调用 First View Controller 中已实现的委托方法。

完整代码。

let storyboard = UIStoryboard(name: “SecondVC”, bundle: Bundle(identifier: “SecondBundle”))
if let controller = storyboard.instantiateInitialViewController() as? SecondVC {
       //Assign Delegate
       controller.delegate = self

       //It's not init, but an assignment only, as per your code.
       controller.initSecondVC(data) 


      self.present(controller, animated: true, completion: nil)
}

还有一件事,不要在 ViewDidLoad 中显示视图。您可以将代码放入某个按钮或延迟方法中。