Search code examples
iosobjective-cuiviewcontrollerxcode-storyboard

Programmatically instantiate custom view controller and getting the subviews by tag


I have three view controllers each under the same custom view controller class, and a page view controller. I want to be able to reuse these three view controllers but with different content on their subviews. However, when I try to instantiate one of these view controllers from the page view controller using [self.storyboard instantiateViewControllerWithIdentifier:identifier], with a method to find the subview by tag right after, the subview returned is null. Is there some way I can get the subview by tag right after instantiating the view controller programmatically?


Solution

  • A view controller's views don't get created until it is about to be displayed. They won't be created after the call to instantiateViewControllerWithIdentifier:

    You should put code that accesses the view controllers views in viewDidLoad, viewWillAppear, or viewDidAppear.

    You should not try to manipulate a view controller's views from an outside object. That violates the principle of encapsulation, an important principle of object-oriented design. (It also often doesn't work, as you found out.)

    If you need do things to the views programmatically you should add one or more public methods to the view controller and call those methods to ask the view controller to make adjustments to its views.