viewWithTag始终在子视图控制器中返回nil

时间:2015-10-26 21:43:19

标签: ios null childviewcontroller viewwithtag

我使用[self.view viewWithTag]来引用UIViewController中的对象。然后我继续将特定的子视图移动到新的UIViewController,然后将其添加为子视图控制器并将视图添加为子视图。但是,现在我无法在子视图控制器中使用viewWithTag来访问不同的对象。每次使用viewWithTag检索的对象都是nil。

我不认为我使用viewWithTag不正确,因为它在将视图移动到新视图控制器之前工作正常。一种解决方案就是为我使用viewWithTag引用的每个视图创建属性,但我认为这不是一个好方法。有更好的解决方案吗?为什么会这样?

根据要求进行修改:

以下是我添加子视图控制器的方法:

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];

以下是创建按钮的代码:

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];

在其他方法中,我正在尝试检索并向该按钮添加目标:

UIButton *updateButton = (UIButton *)[self.view viewWithTag:5];
[updateButton addTarget:self action:@selector(updateCurrentDictionaryWithRuneInfo) forControlEvents:UIControlEventTouchUpInside];

当我添加断点和po updateButton时,它返回为零。同样的事情发生在视图控制器中的其他UI元素,我也试图以这种方式检索。

1 个答案:

答案 0 :(得分:0)

我明白了。 updateButton被添加到另一个UIView中,该UIView被添加到父视图控制器中。因此,为了检索updateButton,我应该使用[self.parentViewController.view viewwithTag:5]而不是[self.view viewWithTag:5]