2012-02-13 42 views
0

如何保护UITableViewCell的文本,UITableViewCell在滚动时被更改。保护UITableView滚动事件的cell.textLabel.text

static NSString *CellIdentifier = @"Cell"; 
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if(indexPath.row != [destinationList count]) 
{ 
    if (cell == nil) 
    { 
     cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.customLable.text = @"MyCustomLabel"; 
else 
{ 
    if (cell == nil) 
    { 
     cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
    } 
    cell.textLabel.text = @"Static Text to be set"; 
    [cell.customLable removeFromSuperview]; 
} 

问题:我每次滚动的UITableView,@ “要设置静态文本” 会被覆盖上@ “MyCustomLabel”。

我该如何预防?我希望UITableView的所有单元通过Table的LifeTime保留它们的TextLabels。

回答

1

两个可能的答案:

  1. 一般也没关系。重复使用单元格是它应该如何工作的,你应该每次完全“重置”每个单元格。你不应该在小区中存储状态反正
  2. 自定义标签创建一个新的reuseIdentifier,一个又一个的静态文本
+0

但是,它改变了我的“MyCustomLabel”到“设置静态文本“(这是另一个单元格的文本)。 – Krishna 2012-02-13 16:40:51

+0

是的,这就是应该发生的事情。它只发生在细胞不再可见时。你可以通过为静态单元使用不同的重用标识符来阻止它。正如我在答复中所说的那样。 – 2012-02-13 16:48:21

+0

什么也没有改变,即使在创建新的reuseIdentifier之后。 – Krishna 2012-02-13 17:10:12

1

他们都将保留其UILabels属性,因为细胞得到重用这就是为什么你使用:

[tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

然而UITableView的使用延迟加载这意味着它仅保留在内存中可见UITableViewCells,因此,当您滚动现在看不见细胞得到重用,现在新的可见细胞与您不能再看到的UILabel具有相同的UILabel。这意味着每次只有少数的UITableViewCell被重用。

这就是为什么在该实例方法prepareforReuse讨论的文档UITableViewCell

如果一个UITableViewCell对象是可重复使用的,也就是说,它有一个复用标识符,该方法被调用时返回的对象之前从UITableView方法dequeueReusableCellWithIdentifier :.出于性能考虑,您应该只重置与内容无关的单元格属性,例如,alpha,编辑和选择状态。 tableView:cellForRowAtIndexPath:中的表视图委托在重用单元时应始终重置所有内容。如果单元对象没有关联的重用标识符,则不调用此方法。如果您重写此方法,则必须确保调用超类实现。

0

您应该为不同的单元格制作不同的标识符。 无论如何,在UITableView中存储的东西是一种错误的方法,它只是显示数据,而不是存储。

0

为什么你删除自定义标签?只要删除标签的文字。

if(indexPath.row != [destinationList count]) 
{ 
    /* ... */ 
    cell.textLabel.text = @""; 
    cell.customLable.text = @"MyCustomLabel"; 
else 
{ 
    /* ... */ 
    cell.textLabel.text = @"Static Text to be set"; 
    cell.customLable.text = @""; 
} 

并确保标签是透明的。

0

试试这个

static NSString *CellIdentifier = @"Cell"; 
CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

if (cell == nil) 
{ 
    cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; 
} 
cell.textLabel.text = nil; 
cell.customLabel.text = nil; 
if(indexPath.row != [destinationList count]) 
{ 
    cell.customLable.text = @"MyCustomLabel"; 
} 
else 
{ 
    cell.textLabel.text = @"Static Text to be set"; 
}