我有一个NewCartViewController
嵌入UINavigationController
在我的ContainerViewController
中:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToCart" {
self.cartVC = segue.destination as? NewCartViewController
self.cartVC?.delegate = self
print("cartVC Delegate", cartVC?.delegate) // value is NOT nil here
let pendingCart = PendingCart(color: .blue)
self.cartVC?.setupPaintOrder(cart: pendingCart)
}
}
在我的NewCartViewController
protocol NewCartViewControllerDelegate: class {
func vcDidFinishWithCancel(_ newCartViewController: NewCartViewController)
}
class NewCartViewController: UIViewController {
weak var delegate: NewCartViewControllerDelegate?
....
@objc func dismissVC() { // called from the leftBarButtonItem
print(delegate) // nil
}
我查看了其他相关的答案,但不确定此处发生了什么。任何帮助,将不胜感激。谢谢!
编辑-有关如何实例化VC的更多详细信息:
我的BuyButtonVC
调用一个委托方法回到AddToCartContainerVC
:
extension AddToCartContainerViewController: BuyButtonViewControllerDelegate {
func buyButtonVCDidPressButton(_ vc: BuyButtonViewController) {
performSegue(withIdentifier: "goToCart", sender: self)
}
}
然后从上方的第一个代码块中触发prepare(for segue:)
函数,我们在其中查看segue.destination
并设置委托。
我在didSet
中的委托人的NewCartViewController
上有打印,并且看到委托已设置。
用户转到屏幕,再也不会像调用didSet
那样再次调用nil
。但是,当我尝试在第二个代码块中调用委托方法时,委托为nil
答案 0 :(得分:0)
我尝试使用以下代码,但似乎工作正常。
很少有几次我们得到这种未知的行为,并且在卡住时感到沮丧。尝试清理构建并退出Xcode清除派生数据,然后再次执行。
class ContainerViewController: UIViewController, NewViewControllerDelegate {
weak var cartVC: NewViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "goToCart" {
self.cartVC = segue.destination as? NewViewController
self.cartVC?.delegate = self
print("cartVC Delegate", cartVC?.delegate) // value is NOT nil here
// let pendingCart = PendingCart(color: .blue)
// self.cartVC?.setupPaintOrder(cart: pendingCart)
}
}
func vcDidFinishWithCancel(_ newViewController: NewViewController) {
print(newViewController.delegate)
self.navigationController?.popViewController(animated: true)
}
}
protocol NewViewControllerDelegate: class {
func vcDidFinishWithCancel(_ newViewController: NewViewController)
}
class NewViewController: UIViewController {
weak var delegate: NewViewControllerDelegate?
@IBOutlet weak var leftBarButtonItem: UIBarButtonItem!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .plain, target: self, action: #selector(dismissVC))
}
@objc func dismissVC() { // called from the leftBarButtonItem
print(delegate) // nil
delegate?.vcDidFinishWithCancel(self)
}
}
输出:单击leftbarbuttonitem时
cartVC Delegate Optional(<NetworkExtensionTest.ViewController: 0x7f84c6d07670>)
Optional(<NetworkExtensionTest.ViewController: 0x7f84c6d07670>)
Optional(<NetworkExtensionTest.ViewController: 0x7f84c6d07670>)