IOS:tableview委托方法为两个tableview
我有一个类的tableview中的这些委托方法:
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [array1 count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil){ cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ; } cell.textLabel.text = [array1 objectAtIndex:indexPath.row]; return cell; }
如果我有一个单一的UITableView它没关系,但如果我有两个UITableView? 我如何组织我的代码? 带标签?
看看所有的委托方法有一个tableView:(UITableView *)tableView
在他们?
你可以在头文件中定义你的表视图,然后简单地去:(假设你的表被称为myTable
)
if (tableView == myTable)
那么你可以有任意多的表格视图,只要你喜欢。
举个例子:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [array1 count]; }
变为:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if (tableView == myTable) { return [array1 count]; } if (tableView == myTable2) { return [array2 count]; } return 0; }
我的build议是让你的数据源充当一个表视图委托,而不是你的控制器。
这是一个更接近模型 – 视图 – 控制器模式的devise,它将允许您更灵活,并避免检查tableView
参数在委托方法中具有的特定值。
在你的情况下,你的委托/数据源将是一个具有NSArray
types成员的类,同时也实现了UITableViewDelegate
协议。
是的,你可以用标签来做。 给你的UITableViews标签1和2。
设置一个开关:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(cell == nil){ cell = [[[UITableViewCell alloc]initWithStyle:UITableViewStylePlain reuseIdentifier:CellIdentifier] autorelease] ; } switch ([tableView tag]) { case 1:{ [[cell textLabel] setText:@"First tag"] break; } case 2:{ [[cell textLabel] setText:@"Second tag"] break; } default: break; } return cell; }
这些方法中的每一个传入一个对调用它的表视图的引用。 我通常将每个表连接到接口构build器中的出口,并根据与委托方法和出口名称中的tableView的比较有条件地返回数据源。 这样做的标签也是可能的,但更麻烦,更复杂的编辑视图结构。