我想添加一个视图控制器视图,它有一个按钮和几个标签作为 uitableviewcell 的内容视图。
虽然我可以添加,但按钮操作会导致崩溃。
MyViewController *controller = [[MyViewController alloc] initwithnibname:@"MyView" bundle:nil];
[cell.contentview addsubview:controller.view];
[controller release]; // if i comment out this part the button action is received by my view controller.
然而,当它从视图中删除时,会出现内存泄漏。 myviewcontroller 的 dealloc 没有被调用。
这样做的正确方法是什么?
将视图添加到 uitableview 单元格
它有一个按钮并由
视图控制器
如何保证内存被释放
当视图超出范围时?
TIA,
普拉文
我认为问题是,您正在释放控制器并仅使用其超级视图保留的子视图。动作模式需要一个目标,我假设它是已发布的控制器。如果你只需要 viewController 的视图,为什么要释放它呢?保留它并通过属性保留对它的引用。
我将子视图添加到表视图单元格的方法是在 UITableViewCell 的子类中。假设您有一个子类UITableViewCell
, say ButtonTableViewCell
。单元格的 init 会创建一个 UIButton 并将其添加到您的单元格中,并将其很好地放入其 contentView 中。 Decalre 引用按钮的属性。喜欢UIButton *myButton
。在 cellForRowAtIndexPath 中应该做的是这样的:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
ButtonTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyButtonCell"];
if (cell == nil) {
cell = [[ButtonTableViewCell alloc] initWithReuseIdentifier:@"MyButtonCell"];
}
[cell.myButton addTarget:self action:@selector(onDoSomething) forControlEvents:UIControlEventTouchUpInside];
// Do more cell configuration...
return cell;
}
我已经编写了初始化程序initWithReuseIdentifier
这可以很容易地实现。
您确保释放内存查看已卸载 http://developer.apple.com/library/ios/documentation/uikit/reference/UIViewController_Class/Reference/Reference.html#//apple_ref/doc/uid/TP40006926-CH3-SW36的方法UI视图控制器 http://developer.apple.com/library/ios/#documentation/uikit/reference/UIViewController_Class/Reference/Reference.html和dealloc方法。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)