SFF*_*SFF 7 objective-c uitableview ios
有一个烦人的错误,我无法解决.
我有一个CustomCell,在其中我有一个子视图,根据对象的值改变它的颜色.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *cellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
MyObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
if ([object.redColor isEqualToNumber:[NSNumber numberWithBool:YES]]) {
cell.colorView.backgroundColor = [UIColor redColor];
}
else {
cell.colorView.backgroundColor = [UIColor clearColor];
}
return cell;
}
Run Code Online (Sandbox Code Playgroud)
这一切都正常,除非我redColor = YES从tableview中删除一行,并滚动显示不可见的行.变为可见的第一行(重用可重用单元格的第一行)具有红色,即使该行是redColor = NO.如果我再次滚动并隐藏单元格然后再次显示它,颜色将设置为clearColor,它应该是这样的.
我认为这是因为它重用了刚被删除的单元格.所以我在重用之前尝试重置单元格的内容.在CustomCell.m
- (void)prepareForReuse {
[super prepareForReuse];
self.clearsContextBeforeDrawing = YES;
self.contentView.clearsContextBeforeDrawing = YES;
self.colorView.backgroundColor = [UIColor clearColor];
}
Run Code Online (Sandbox Code Playgroud)
但这不起作用.Apple Doc说
tableView中的表视图委托:cellForRowAtIndexPath:在重用单元格时应始终重置所有内容.
重置内容的正确方法是什么?我是否必须从超视图中删除子视图?
提前致谢
SFF*_*SFF 13
这似乎有效.
我在prepareForReuse中删除了单元格的contentView CustomCell.m
- (void)prepareForReuse {
[super prepareForReuse];
// Clear contentView
BOOL hasContentView = [self.subviews containsObject:self.contentView];
if (hasContentView) {
[self.contentView removeFromSuperview];
}
}
Run Code Online (Sandbox Code Playgroud)
再次添加 cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
// Cell
static NSString *cellIdentifier = @"CustomCell";
CustomCell *cell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
if (cell == nil) {
cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
}
// Restore contentView
BOOL hasContentView = [cell.subviews containsObject:cell.contentView];
if (!hasContentView) {
[cell addSubview:cell.contentView];
}
// Configure cell
MyObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
if ([object.redColor isEqualToNumber:[NSNumber numberWithBool:YES]]) {
cell.colorView.backgroundColor = [UIColor redColor];
}
else {
cell.colorView.backgroundColor = [UIColor clearColor];
}
return cell;
}
Run Code Online (Sandbox Code Playgroud)
希望这会对某人有所帮助.
| 归档时间: |
|
| 查看次数: |
13386 次 |
| 最近记录: |