繁体   English   中英

nil在具有两个不同Bundle(Swift)的两个ViewController之间委托

[英]nil Delegate between two ViewController with two different Bundle (swift)

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

这是我的代码:

第一个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显示View。 您可以将代码放在某些按钮或延迟方法中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM