Jos*_*ane 6 iphone objective-c uitableview ipad
我正在组装一个TableView,我需要在同一个表中使用多个单元类.
那么例如我如何在我的cellForRowAtIndexPath方法中使用多个单元类?
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
// Configure the cell...
return cell;
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以简单地UITableViewCell用我的自定义类替换并使用if语句根据索引来调整类,但是不是有点乱,什么是合理的,可能是最聪明的方法呢?
当然可以.只需创建自定义单元格的新实例并为其提供新的CellId.
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if (condition1)
{
static NSString *CellIdentifier1 = @"Cell1";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier1];
// TODO: if cell is null, create new cell of desired type.
// This is where you create your custom cell that is
// derived form UITableViewCell.
}
else
{
static NSString *CellIdentifier2 = @"Cell2";
UITableViewCell *cell =
[tableView dequeueReusableCellWithIdentifier:CellIdentifier2];
//TODO: if cell is null, create new cell of desired type
}
// Configure the cell...
return cell;
}
Run Code Online (Sandbox Code Playgroud)
您可以通过将表定义为在其.xib文件或Storyboard中包含多个原型单元来完成此操作.请注意以下Xcode屏幕截图中的表视图设置"Dynamic Prototypes":

必须为每个原型单元提供唯一的重用标识符.在该示例中,第一小区类型具有重用标识符@"ScanCell",第二小区类型具有重用标识符@"DetailCell".然后,在您的-tableView:cellForRowAtIndexPath:方法中,您只需通过选择要传递给哪个重用标识符来选择要使用的单元类-dequeueReusableCellWithIdentifier:.
以下是我自己的一个应用程序的示例:
- (UITableViewCell *)tableView:(UITableView *)tableView
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString * cellIdentifier = @"DetailCell";
if ([indexPath section] == 0) {
cellIdentifier = @"ScanCell";
}
UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier
forIndexPath:indexPath];
if ([indexPath section] == 1) {
CBPeripheral * peripheral = (CBPeripheral *)[self.appDelegate.peripherals objectAtIndex:[indexPath row]];
cell.textLabel.text = [peripheral name];
cell.detailTextLabel.text = [self.appDelegate.peripheralKeys objectAtIndex:[indexPath row]];
}
return cell;
}
Run Code Online (Sandbox Code Playgroud)
如果您希望原型单元格具有不同的类,只需在.xib或Storyboard文件中设置它们的类.
| 归档时间: |
|
| 查看次数: |
6404 次 |
| 最近记录: |