ios - 布局自定义 UITableViewCell 的问题

标签 ios uitableview

我创建了一个 UITableView带有自定义UITableViewCell来自NIB。在加载 View Controller 时,一切似乎都正常。但是当我开始滚动 UITableView ,有些情况下,一个空单元格会无缘无故地出现在中间。

我不知道发生了什么。我的 cellForRowAtIndexPath很简单。但是我在自定义 UITableViewCell 中添加了手势。 .这会导致问题吗?
这是我的代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *tableIdentifier = @"FTStreamCell";
    FTStreamCell *cell = (FTStreamCell *)[tableView dequeueReusableCellWithIdentifier:tableIdentifier];
        if (cell == nil)
        {
            NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"FTStreamCell" owner:self options:nil];
            cell = [nib objectAtIndex:0];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleGray;
        cell.delegate = self;
        return cell;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    FTStreamCell *streamCell = (FTStreamCell*) cell;
    if (!indexPath.section == 0)
    {
        if ((NSNull*)[[[self.cachedData objectForKey:kQuestions] objectAtIndex:indexPath.row] objectForKey:kQuestion] != [NSNull null])
            streamCell.question.text = [[[self.cachedData objectForKey:kQuestions] objectAtIndex:indexPath.row] objectForKey:kQuestion];
        streamCell.timePosted.text = [NSString stringWithFormat:@"Today at Bangalore, India"];
        // To Show My Questions
        NSLog(@"Me %d", [[[NSUserDefaults standardUserDefaults] objectForKey:kUserId] integerValue]);
        if ([[[self.cachedData objectForKey:kQuestions] objectAtIndex:indexPath.row] objectForKey:kUserId] == [[NSUserDefaults standardUserDefaults] objectForKey:kUserId])
        {
            streamCell.mainView.backgroundColor = [UIColor colorWithRed:244.0f/255.0f green:240.0f/255.0f blue:247.0f/255.0f alpha:1];
            streamCell.userCheck = YES;
        }
        else
        {
            streamCell.mainView.backgroundColor = [UIColor colorWithRed:255.0f/255.0f green:255.0f/255.0f blue:255.0f/255.0f alpha:1];
            streamCell.userCheck = NO;
        }
        [cell layoutSubviews];
    }
}

谢谢。

最佳答案

UITableViews 重用表格单元以减少内存分配。因此,当您开始滚动时,“白色单元格”可能是以前使用和修改过的单元格。在 willDisplayCell 方法中,在应用风格更改之前尝试“重置”单元格。 “重置”将是您的自定义方法,可将单元格中的所有内容更改回默认值。

关于ios - 布局自定义 UITableViewCell 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21622278/

相关文章:

ios - Facebook Graph API 更改了今天的结果/帖子?

iphone - 如何在自定义单元格中使用 autoresizingMask 制作 UILabel?

objective-c - 委托(delegate)方法 'canMoveRowAtIndexPath' 的目的是什么?

ios - UIButton.titleLabel.frame.size 始终为零值

ios - 我第一次单击单元格时,需要一些时间来加载下一个 View Controller 。为什么?

ios - 什么是比例以及为什么在使用 UIPinchGestureRecognizer 时必须重置它?

ios - didSelectRowAtIndexPath 执行后 UITableViewCells 消失了吗?

ios - 添加并布局从 xib 加载到自定义单元格的 subview

ios - UITableViewController selectionStyle 无不工作

ios - mergeChangesFromContextDidSaveNotification 后的 KVO 通知