[英]Xcode: add TableView into custom Cell
我正在尝试做某事,但都没有在网络上找到任何示例,也不知道是否有可能。
我需要以编程方式将表添加到tbaleview的第一个单元格中。
当我尝试设置第二个表(第一个表中的一个)的委托和数据源时,代码给我带来了问题
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
[[NSBundle mainBundle] loadNibNamed:@"CellaMenu" owner:self options:NULL];
cell = cellaMenu;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = NO;
tabellaMenu = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
tabellaMenu.dataSource = self;
tabellaMenu.delegate = self;
[cell.contentView addSubview:tabellaMenu];
}
这样,代码循环。 如果不设置委托和数据源,则将显示该表,但我需要它们来创建自定义处理程序。 有什么提示吗?
最干净的方法是在视图控制器中具有另一个符合UITableViewDataSource和UITableViewDelegate的对象,然后将第二个表视图的委托和dataSource设置为此对象。
代码进入循环,因为单元格中的tabellaMenu表已将委托和数据源设置为self。 因此,它继续自行调用表数据源方法,并创建新的单元格并进入循环。
您可以创建一个单独的对象(NSObject的子类),然后在其中定义表委托和数据源方法,并将其设置为tabellaMenu的委托和数据源。
或者,您可以创建UITableViewCell的子类并以编程方式在其中创建表视图。 定义表的数据源并在其中委托方法。 因此,该单元格中的每个表视图都将引用其自己的单元格进行数据源和委托。 此外,每次主表重新加载时,您都会获得-(void)prepareForReuse(如果单元格可重用)以在单元格中重新加载表。
在-tableView:cellForRowAtIndexPath:
内部,您可以在创建单元格后编写以下代码。
//if first row & table is not present already
if (indexPath.row == 0 && ![cell.contentView viewWithTag:5]) {
UITableView *tabellaMenu =
[[UITableView alloc] initWithFrame:self.contentView.bounds
style:UITableViewStylePlain];
tabellaMenu.tag = 5;
tabellaMenu.dataSource =tabellaMenuDataSource;
tabellaMenu.delegate = tabellaMenuDelegate;
[cell.contentView addSubview:tabellaMenu];
}
方法如下:
如果仅在第一个单元格中需要tableView
,则可以全局使用它,而不必在cellForRowAtIndexPath:
方法中进行初始化,因为它在滚动期间每次都被调用。
UITableView *mainTableView;
UITableView *childTableView;
现在,您可以通过比较它们的实例,轻松地在它们的delegates
和datasources
方法中区分这两个表。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
if (tableView == mainTableView) {
// Do code for your main tableView
if (indexPath.row == 0) {
[[NSBundle mainBundle] loadNibNamed:@"CellaMenu" owner:self options:NULL];
cell = cellaMenu;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
cell.userInteractionEnabled = NO;
if (!childTableView) {
// Initialise only if it is nil (not initialised yet)
childTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
childTableView.dataSource = self;
childTableView.delegate = self;
}
[cell.contentView addSubview:childTableView];
}
}
else {
// Do code for your child tableView
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.