书上告诉我应该使用UITableView单元格的重用标识符
//check for reusable cell of this type
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
//if there isn't one, create it
if(!cell){
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
reuseIdentifier: @"UITableViewCell"];
}
从我看到的,它检查我们想要的单元格类型是否存在,如果存在,它就使用它,但如果不存在,它就用那个想要的标识符创建一个。
如果我们有多个单元格样式(即不同的reuseIdentifiers),我们将如何使用它来为我们创建不同的可重用单元格?
表视图管理单独的单元格队列,以便对每个标识符进行重用。因此,例如,如果单元格的偶数行和奇数行应该具有不同的外观(仅作为示例),则可以执行
NSString *cellIdentifier = (indexPath.row % 2 == 0 ? @"EvenCell" : @"OddCell");
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault
reuseIdentifier:cellIdentifier];
if (indexPath.row % 2 == 0) {
// set cell properties for even rows
} else {
// set cell properties for odd rows
}
}
使用不同的重用标识符可以保证不重用偶数行的单元格作为奇数行的单元格。
(此示例仅在不插入或删除单元格的情况下才有效。另一个例子是不同的单元格取决于内容的行)
indexPath
,使用它。它包含行和节,所以无论你想设置什么属性,你都可以从行和节中选择大小写,并相应地设置。