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

时间:2019-05-01 07:18:47

标签: ios swift delegates bundle

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

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

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