我创建了一个 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/