如何在TableViewCell中创建子表视图

我有一个显示域列表的TableView:

- (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.tableView.dataSource = mainClass.domainList; } 

域列表设置如下:

 -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.domainList count]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [[UITableViewCell alloc] init]; cell.textLabel.text = [[self.domainList objectAtIndex:indexPath.row] name]; return cell; } 

这非常有效,它在我的表视图的一行中显示每个域。

现在我想在我的表视图的每个单元格中添加一个“Sub TableView”来显示与域相关的文档列表。 我试过了:

  -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableView *table = [[UITableView alloc] init]; table.dataSource = [self.domainList objectAtIndex:indexPath.row]; UITableViewCell *cell = [[UITableViewCell alloc] init]; cell.textLabel.text = [[self.domainList objectAtIndex:indexPath.row] name]; [cell.contentView addSubView table] return cell; } 

它不会崩溃,但它也不起作用。 我的意思是子列表不会出现在任何地方。 我究竟做错了什么?

datasource必须是实现协议UITableViewDataSource的类。 看起来您将其设置为自定义对象。 使用用于实现第一个表的代码创建单独的类,然后将子列表设置为源数据。 在objc.io文章“ 干净的表视图代码 ”中,他们解释了如何制作可重用的数据源。 或者你可以自己尝试一下。

考虑以下代码:

 // ARRAYDATASOURCE.H #import  typedef void (^TableViewCellConfigureBlock)(id cell, id item); @interface ArrayDataSource : NSObject  -(id) init __attribute__((unavailable("disabled, try initWithItems:cellIdentifier:configureCellBlock"))); - (id) initWithItems:(NSArray *)anItems cellIdentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock; - (id)itemAtIndexPath:(NSIndexPath *)indexPath; @end // ARRAYDATASOURCE.M #import "ArrayDataSource.h" @interface ArrayDataSource () @property (nonatomic, strong) NSArray *items; @property (nonatomic, copy) NSString *cellIdentifier; @property (nonatomic, copy) TableViewCellConfigureBlock configureCellBlock; @end @implementation ArrayDataSource - (id)initWithItems:(NSArray *)anItems cellIdentifier:(NSString *)aCellIdentifier configureCellBlock:(TableViewCellConfigureBlock)aConfigureCellBlock { self = [super init]; if (self) { self.items = anItems; self.cellIdentifier = aCellIdentifier; self.configureCellBlock = [aConfigureCellBlock copy]; } return self; } - (id)itemAtIndexPath:(NSIndexPath *)indexPath { return self.items[(NSUInteger) indexPath.row]; } #pragma mark UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.items.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath]; id item = [self itemAtIndexPath:indexPath]; self.configureCellBlock(cell, item); return cell; } @end