如何正确重用目标 c 中的单元格?



我的UITableViewCell有一个大问题。我使用故事板,并且在我的UITableVIew中有一个自定义单元格。我为此添加一个标识符,我的类代码是:

static NSString *celldentifier = @"myCellId";
CustomCell *myCell = [tableView dequeueReusableCellWithIdentifier:celldentifier];
if (celldentifier == nil) {
celldentifier = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:celldentifier];
}
...

编辑:

...
myCell.myButton.hidden = YES;
...

当我在单元格中加载其他信息并且需要隐藏按钮时,我会做一个重新加载表:

[self.myTable reloadData];

在我的视图中控制器,我重新加载了这个表视图,显示或隐藏了我单元格中的一些组件,如 UIButton。但是当我滚动时,添加的这个按钮消失了。

我的代码出了什么问题?我该如何解决这个问题?

问题是单元格被重用了.. 如果你有一个if 语句要进行更改.. 确保已经放置了 else 以便你恢复它

if(isReady){
myCell.myButton.hidden = YES;
}
else {
myCell.myButton.hidden = NO;
}
static NSString *celldentifier = @"myCellId";
CustomCell *myCell = [tableView dequeueReusableCellWithIdentifier:celldentifier];
if (!myCell) {
myCell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:celldentifier];
}

myCell.myButton.hidden = YES;

cellForRowAtIndexPath方法中使用它是个坏主意。

您应该为单元格创建模型并保留单元格的所有属性。

if (myCell == nil) {
myCell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:celldentifier];
//I think it should be but don't shure
//[tableView registerClass:<#(nullable Class)#> forCellReuseIdentifier:<#(nonnull NSString *)#>];
}

我遇到了同样的问题,您应该在myCell.myButton.hidden = YES;之前添加myCell.myButton.hidden = NO;此代码

喜欢这个:

static NSString *simpleTableIdentifier = @"myCellId";
CustomCell * myCell = (CustomCell *)[tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
if (myCell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"CustomCell" owner:self options:nil];
myCell = [nib objectAtIndex:0];
}
myCell.myButton.hidden = NO;
if(isReady){
myCell.myButton.hidden = YES;
}

相关内容

最新更新