I was using [self.view viewWithTag]
in order to reference objects within a UIViewController. I then proceeded to move a specific subview to a new UIViewController, then adding it as a child view controller and adding the view as a subview. However, now I am unable to use viewWithTag
within the child view controller to access different objects. Each time, the object retrieved using viewWithTag
is nil.
I don't think that I am using viewWithTag improperly, as it was working fine before I moved that view to the new view controller. One solution is just to create properties for each of the views that I'm referencing using viewWithTag
, but I do not think that this is a good way. Is there a better solution? Why is this happening?
Edit, as requested:
Here is how I add the child view controller:
self.runeTable = [RuneTableViewController new];
[self addChildViewController:self.runeTable];
self.runeTable.view.frame = CGRectMake(screenshotWidth + 32, navBarHeight, self.view.frame.size.width-screenshotWidth-32.0, self.view.frame.size.height-navBarHeight);
[self.view addSubview:self.runeTable.view];
Here is the code for creating the button:
UIButton *updateButton = [UIButton buttonWithType:UIButtonTypeCustom];
updateButton.tag = 5;
[updateButton setTitleColor:HIGHLIGHT_COLOR forState:UIControlStateNormal];
[updateButton.titleLabel setFont:FONT_MED_LARGE_BOLD];
[updateButton setTitle:@"Update" forState:UIControlStateNormal];
updateButton.frame = CGRectMake(283, 280-60, 100, 60);
[detailInnerView addSubview:updateButton];
And here in some other method, I am trying to retrieve and add a target to that button:
UIButton *updateButton = (UIButton *)[self.view viewWithTag:5];
[updateButton addTarget:self action:@selector(updateCurrentDictionaryWithRuneInfo) forControlEvents:UIControlEventTouchUpInside];
When I added breakpoint and po updateButton
, it returned as nil. Same thing happened with other UI elements in the view controller that I also tried to retrieve in this manner.
I figured it out. updateButton
is added to another UIView, which is added to the parent view controller. Thus, in order to retrieve updateButton I should be using [self.parentViewController.view viewwithTag:5]
instead of [self.view viewWithTag:5]
.