From within a view controller in a container view, how do you access the view controller containing the container?

前端 未结 7 2012
南笙
南笙 2020-12-28 13:14

This is tricky to word but I have a view controller (vc1) that contains a container view (I\'m using storyboards). Within that container view is a navigation controller and

7条回答
  •  一生所求
    2020-12-28 13:36

    Swift - An alternative is to create a reference in parent UIViewController (vc1) to child/subview UIViewController (vc2) and in vc2 to vc1. Assign the references in parent(vc1) viewDidLoad() example below.

    Parent UIViewController vc1:

          class vc1: UIViewController {
    
              @IBOutlet weak var parentLabel: UILabel!
              var childVc2: vc2?;
    
               overide func viewDidLoad() {
                   super.viewDidLoad();
                   // Use childViewControllers[0] without type/class verification only 
                   // when adding a single child UIViewController 
                   childVc2 = self.childViewControllers[0] as? vc2;
                   childVc2?.parentVc1 = self
               }
          }
    

    Child UIViewController vc2:

          class vc2: UIViewCortoller {
              var parentVc1: vc1?;
    
              // At this point child and parent UIViewControllers are loaded and 
              // child views can be accessed
              override func viewWillAppear(_ animated: Bool) {
                 parentVc1?.parentLabel.text = "Parent label can be edited from child";
              }
          } 
    

    In the Storyboard remember to set in Identity Inspector the parent UIViewContoller class to vc1 and child UIViewContoller class to vc2. Ctrl+drag from Container View in vc1 UIViewController to vc2 UIViewController and select Embed.

提交回复
热议问题