UITableView:如何利用单元重用标识符?

时间:2013-06-04 05:12:26

标签: objective-c uitableview ios4

我的书告诉我,我应该使用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"]; 
}   

所以从我看到的,它检查我们想要的单元格类型是否存在,如果存在,它会使用它,但如果它没有,它会创建一个具有所需标识符的单元格。

如果我们有多个单元格样式(即不同的reuseIdentifier),我们如何使用它为我们创建不同的可重用单元格呢?

2 个答案:

答案 0 :(得分:3)

表视图管理单独的单元队列,以便为每个标识符重用。因此,例如,如果单元格对于偶数行和奇数行应具有不同的外观(仅作为示例),您可以这样做

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
    }
}

使用不同的重用标识符可确保不重用偶数行中的单元格 作为奇数行的单元格。

(此示例仅在您不插入或删除单元格时才有效。另一个示例是不同的单元格,具体取决于行的内容。)

答案 1 :(得分:0)

indexPath,请使用它。它包含您的行和部分,因此您要设置的任何属性都可以从行和部分中选择案例并相应地进行设置。

相关问题