Access Container View Controller from Parent iOS

后端 未结 11 2131
遥遥无期
遥遥无期 2020-11-28 18:13

in iOS6 I noticed the new Container View but am not quite sure how to access it\'s controller from the containing view.

Scenario:

相关标签:
11条回答
  • 2020-11-28 18:28

    I use Code like:

    - (IBAction)showCartItems:(id)sender{ 
      ListOfCartItemsViewController *listOfItemsVC=[self.storyboard instantiateViewControllerWithIdentifier:@"ListOfCartItemsViewController"];
      [self addChildViewController:listOfItemsVC];
     }
    
    0 讨论(0)
  • 2020-11-28 18:31

    you can write like this

    - (IBAction)showDetail:(UIButton *)sender {  
                DetailViewController *detailVc = [self.childViewControllers firstObject];  
            detailVc.lable.text = sender.titleLabel.text;  
        }  
    }
    
    0 讨论(0)
  • 2020-11-28 18:40

    You can do that simply with self.childViewControllers.lastObject (assuming you only have one child, otherwise use objectAtIndex:).

    0 讨论(0)
  • 2020-11-28 18:43

    The prepareForSegue approach works, but it relies on the segue identifier magic string. Maybe there's a better way.

    If you know the class of the VC you're after, you can do this very neatly with a computed property:

    var camperVan: CamperVanViewController? {
      return childViewControllers.flatMap({ $0 as? CamperVanViewController }).first
      // This works because `flatMap` removes nils
    }
    

    This relies on childViewControllers. While I agree it could be fragile to rely on the first one, naming the class you seek makes this seem quite solid.

    0 讨论(0)
  • 2020-11-28 18:43

    An updated answer for Swift 3, using a computed property:

    var jobSummaryViewController: JobSummaryViewController {
        get {
            let ctrl = childViewControllers.first(where: { $0 is JobSummaryViewController })
            return ctrl as! JobSummaryViewController
        }
    }
    

    This only iterates the list of children until it reaches the first match.

    0 讨论(0)
提交回复
热议问题