Ios 滚动显示表格视图时出现故障/错误

Ios 滚动显示表格视图时出现故障/错误,ios,objective-c,uitableview,Ios,Objective C,Uitableview,我的UITableView出现了一个奇怪的小故障/bug。但是,当我向下滚动到第二个单元格并返回到第一个单元格时,第一个单元格中的标签文本与第二个单元格中的标签文本相同……我不太清楚为什么会发生这种情况。请查看我的代码并帮我解决 代码 尝试替换此代码: UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(10,10,300,20)]; titleL.text = myTitle; [cell addSubvie

我的UITableView出现了一个奇怪的小故障/bug。但是,当我向下滚动到第二个单元格并返回到第一个单元格时,第一个单元格中的标签文本与第二个单元格中的标签文本相同……我不太清楚为什么会发生这种情况。请查看我的代码并帮我解决

代码


尝试替换此代码:

UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(10,10,300,20)];
    titleL.text = myTitle;

    [cell addSubview:titleL];
到willDisplayCellForRowAtIndexPath:方法。您的两个单元格中的标签文本相同,因为您的第二个单元格与其所有子视图从第一个单元格中退出队列

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
     static NSString* cellId = @"messagesCell";
     UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellId];
     if (!cell)
         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];

     return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(10,10,300,20)];
    titleL.text = myTitle;

    [cell addSubview:titleL];
}
您以错误的方式创建tableViewCell。每次重新加载表视图时,都会创建一个标签并将其添加到单元格中。因此,如果您向下和向上滚动,您可能会看到许多标签。您应该只创建一个标签并重新使用它。请尝试以下代码

if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(10,10,300,20)];
    titleL.tag = 1234;
    [cell.contentView addSubview:titleL];
}

UILabel *titleL = (UILable*)[cell.contentView viewWithTag:1234];
titleL.text = myTitle;

当我使用该方法时,它不会显示任何内容。您正在alloc/initing和addsubb在tableView:CellForRowatineXpath中查看UILabel。这意味着每次在滚动时调用此方法时,将添加越来越多的标签。要么使用故事板和自定义单元格,要么将代码移动到if cell==nil部分。还有,我的头衔是什么?这是一个全局变量吗?您是否尝试过任何类型的调试来检查myTitle是否被正确地设置为正确的索引路径?
if (cell == nil)
{
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifer];
    UILabel *titleL = [[UILabel alloc] initWithFrame:CGRectMake(10,10,300,20)];
    titleL.tag = 1234;
    [cell.contentView addSubview:titleL];
}

UILabel *titleL = (UILable*)[cell.contentView viewWithTag:1234];
titleL.text = myTitle;