防止UITableViewCells重复内容

我有以下代码,有2个部分。 我希望第一部分有3个单元格,有文本,第二部分没有文字。 问题是在第2节中的第6个细胞之后,细胞重复第1节中的文本。

所以我的单元格如下:第1部分 – 配置文件,联系人,设置; 第2节 – 空白,空白,空白,空白,配置文件,联系人,设置。

我究竟做错了什么?

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 2; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { if(section == 0) return 3; else return 9; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"LeftMenuCell"; UITableViewCell *cell = (UITableViewCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if(indexPath.section == 0) { switch (indexPath.row) { case 0: cell.textLabel.text = @"Profile"; break; case 1: cell.textLabel.text = @"Contacts"; break; case 2: cell.textLabel.text = @"Settings"; break; default: break; } } else { //nothing should appear in these cells } return cell; } 

滚动时重用表视图单元格,即dequeueReusableCellWithIdentifier可以返回先前用于显示不同行的单元格。

因此,您必须显式设置内容,即使在else-case中:

 } else { //nothing should appear in these cells cell.textLabel.text = @""; } 

这是由于细胞重用造成的。 设置cell.textLabel.text = @""; 在不需要显示文本的情况下。

 if(indexPath.section == 0) { //Your code // .... } else { cell.textLabel.text = @""; } 

当你使用Allocs细胞时使用它

 static NSString *CellIdentifier = @"LeftMenuCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell=[[UITableViewCell alloc]initWithStyle: UITableViewCellStyleDefault reuseIdentifier:CellIdentifier]; } 

细胞被重复使用。 看到这个dequeueReusableCell

 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

这是因为Tableview Cell被重用,所以你需要添加这个cell.textLabel.text = @""; 在你的其他条件。 这意味着第二部分。