0

I create a controller from storyboard with a tableView in it.

After I compile and run it, the tableView will be shown, but when I use self.view.subviews to get its subviews in the viewDidLoad method, I can not find the tableView.

Additionally, I try performing the method [self.tableView removeFromSuperview] in viewDidLoad, but the tableView will still be shown at last.

It seems when the viewDidLoad performed, the tableView has not been added the the super view yet. However, in another controller created by storyboard as well, I can get the tableView using self.view.subviews in viewDidLoad...

I am wondering what lead to this and when will the tableView be added.

wkx
  • 431
  • 1
  • 4
  • 7
  • when I use self.view.subviews in viewDidAppear, both of the controllers return me the tableView, but why not in viewDidLoad? – wkx Apr 19 '16 at 07:26
  • 1
    Are you calling super in your viewDidLoad before checking the tableView's status? – Ali Beadle Apr 19 '16 at 07:35
  • Hi, did you connect in IB vc class? Pls check if you did it right. – Alex Kosyakov Apr 19 '16 at 13:51
  • @AliBeadle What do you mean?? – wkx Jun 11 '16 at 14:42
  • @wkx I am wondering whether some part of the view's viewDidLoad prices needs to occur for the tableView to complete being added. I am not sure, so this is not necessarily an answer, but if you have not already, try calling super.viewDidLoad at the beginning of your viewDidLoad overload. – Ali Beadle Jun 11 '16 at 16:32

1 Answers1

0

Ignore my comment, I don't think calling super is the answer (although it is still generally good practice).

The documentation is not clear but the only thing you appear to be able to rely on in viewDidLoad is that the view itself has loaded, not any of its subviews, which as you have discovered may or may not be.

If you do need to access the sub views they are guaranteed to be present at viewDidLayoutSubviews as described in this SO answer but be aware that this will get called whenever the sub views are layed out, which will be multiple times in a typical app lifespan (e.g. it will also get called when the user rotates their device).

If you really need to get at the sub view as soon as it is loaded, you could subclass it and override its own viewDidLoad method.

Community
  • 1
  • 1
Ali Beadle
  • 4,486
  • 3
  • 30
  • 55