我正在使用带有原型单元的故事板:
之后我添加了子视图的动态计数:
问题有时白色屏幕出现在uitableviewcell的一半然后滚动。
并且单元格== nil未调用。
或者只是解释如何将子视图的动态计数添加到uitableviewcell。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *cellIdentifer;
cellIdentifer = @"PhotoWorkCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifer];
if (cell == nil){
NSLog(@"is nil");
}
[self addSubviews:cell atIndexPath:indexPath];
[self configureCell:cell atIndexPath:indexPath];//just setting images and text to views
return cell;
}
-(void)addSubviews:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath{
PhotoWork *work = [self.tableData objectAtIndex:indexPath.row];
PhotoWorkCell *workCell = (PhotoWorkCell*)cell;
for(UIView *view in workCell.contentView.subviews){
if ([view isKindOfClass:[CustomPoints class]])
[view removeFromSuperview];
}
for(int i=0; i <[work.pointsArray count];i++)
{
NSArray *subviewArray = [[NSBundle mainBundle] loadNibNamed:@"CustomPoints" owner:self options:nil];
CustomPoints *customPoints = [subviewArray objectAtIndex:0];
customPoints.frame = CGRectMake(10, 135+i*customPoints.frame.size.height, customPoints.frame.size.width, customPoints.frame.size.height);
customPoints.label= @"test";
workCell.photoButton.tag = indexPath.row;
[workCell.photoButton addTarget:self action:@selector(onHistory:) forControlEvents:UIControlEventTouchDown];
[workCell.contentView addSubview:customPoints];
}
}
- (CGFloat)tableView:(UITableView *)t heightForRowAtIndexPath:(NSIndexPath *)indexPath {
PhotoWork *work = [self.tableData objectAtIndex:indexPath.row];
return 135+[work.pointsArray count]*57;
}
答案 0 :(得分:0)
来自Apple的dequeueReusableCellWithIdentifier:
方法文档:
This method dequeues an existing cell if one is available or creates a new one using the class or nib file you previously registered. If no cell is available for reuse and you did not register a class or nib file, this method returns nil.
这意味着,如果存在具有该标识符的单元格,该方法将永远不会返回nil,而是通过初始化方法initWithStyle:reuseIdentifier:
为您初始化单元格。
然后从UITableViewCell
的方法prepareForReuse
的文档:
The table view's delegate in tableView:cellForRowAtIndexPath: should always reset all content when reusing a cell.
这意味着您应该在addSubviews:atIndexPath:
方法中添加新的子视图之前删除它可能具有的其他子视图。
你可以这样做:
NSMutableArray* tmpArray = [NSMutableArray arrayWithArray:workCell.contentView.subviews];
然后,假设您添加到contentView的唯一额外子视图是此CustomPoints,只需执行:
[tmpArray removeObject:tmpArray.lastObject];
workCell.contentView.subviews = tmpArray;
相反,如果您想要安全,请执行以下操作:
__block NSInteger foundIndex = NSNotFound;
[tmpArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isKindOfClass:[CustomPoints class]]) {
foundIndex = idx;
// stop the enumeration
*stop = YES;
}
}];
if (foundIndex != NSNotFound){
[tmpArray removeObjectAtIndex:foundIndex];
workCell.contentView.subviews = tmpArray;
}
请告诉我这是否对您有用!