nil在两个ViewController之间委派两个不同的Bundle(swift)

问题描述 投票:0回答:1

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

这是我的代码:

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

任何帮助,将不胜感激

ios swift delegates bundle
1个回答
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。您可以将代码放在某个按钮或延迟方法中。

© www.soinside.com 2019 - 2024. All rights reserved.