权CellIdentifier在UITableView中

问题描述:

小区有人能解释权CellIdentifier在UITableView中

static NSString* CellIdentifier = @"Cell"; 

NSString *CellIdentifier = [NSString stringWithFormat: @"Cell%i", indexPath.row]; 

之间的差值。当我应该使用第一个,其中第二?

+0

你能提供一些背景?你在哪里看到这些? – 2012-04-04 17:15:47

+0

第二种方法在任何情况下都更好,因为所有单元都应该按照其'indexPath.row'拥有自己的唯一单元标识符。 – 2012-04-04 17:20:37

+0

我有这样的上下文的单元格:图像和文本。我使用了第一种cellidentifier。因此,tableview不能正常工作,单元格*混合*有时当我滚动tableview(我的意思是一个单元格被复制3或2次在屏幕上),然后我已经改变cellIdentifier为第二种类型,和tableview工作正常。 – Buron 2012-04-04 17:21:56

static NSString* CellIdentifier = @"Cell"; 

这个标识符(假设没有其他人)将确定细胞的池中,当他们需要一个新小区的所有行会拉。

NSString *CellIdentifier = [NSString stringWithFormat: @"Cell%i", indexPath.row]; 

此标识符将创建细胞池的每一行,即,它会造成尺寸1的池对于每一行,而且一个单元将总是仅用于该行。

通常您会希望始终使用第一个示例。第二个示例中的变化如下:

NSString *CellIdentifier = [NSString stringWithFormat: @"Cell%i", indexPath.row % 2]; 

如果您希望每隔一行都具有某种背景颜色或某种类型的颜色,将会很有用。

如何正确地从here建立单元创建一个例子:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyIdentifier"]; 

    if (cell == nil) { 
     cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"MyIdentifier"] autorelease]; 
     cell.selectionStyle = UITableViewCellSelectionStyleNone; 
    } 

    NSDictionary *item = (NSDictionary *)[self.content objectAtIndex:indexPath.row]; 
    cell.textLabel.text = [item objectForKey:@"mainTitleKey"]; 
    cell.detailTextLabel.text = [item objectForKey:@"secondaryTitleKey"]; 
    NSString *path = [[NSBundle mainBundle] pathForResource:[item objectForKey:@"imageKey"] ofType:@"png"]; 
    UIImage *theImage = [UIImage imageWithContentsOfFile:path]; 
    cell.imageView.image = theImage; 

    return cell; 
} 
+0

感谢您的优秀解释! – Buron 2012-04-04 18:00:13