gpt4 book ai didi

ios - TableView 滚动/dequeueReusableCell 问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:15:00 25 4
gpt4 key购买 nike

我有一个表格 View 和一个自定义单元格。该单元格包含 3 个按钮(复选框类型)。在按钮上单击我需要更改的相应按钮文本(选中/取消选中)。我做到了这一点,但是当我单击顶部单元格上的第一个按钮并向下滚动时,底部的新单元格也有此复选标记,当我滚动回顶部时,复选标记移至下一个单元格..如何解决这个问题? ?

代码:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

static NSString *strCellIdentifier = @"RemoteCell";


RemoteCustomCell *cell = (RemoteCustomCell*)[tableView ![dequeueReusableCell][2]WithIdentifier:strCellIdentifier];
if (cell == nil) {
cell = [[RemoteCustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCellIdentifier];
}
else {
cell = [cell initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strCellIdentifier];
}

[cell.btnCheck1 addTarget:self action:@selector(CheckButton1_Click:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;

}


- (void)CheckButton1_Click:(UIButton*)sender
{
RemoteControllCustomCell *clickedCell = (RemoteControllCustomCell *)[[sender superview] superview];

if(clickedCell.btnCheck1.selected)
{
[clickedCell.btnCheck1 setTitle:@"O" forState:UIControlStateNormal];
clickedCell.btnCheck1.selected = NO;
}
else
{
[clickedCell.btnCheck1 setTitle:@"X" forState:UIControlStateSelected];
clickedCell.btnCheck1.selected = YES;
}
}

截图:

enter image description here

enter image description here

最佳答案

在您的 RemoteCustomCell.m 文件中您应该实现

- (void)prepareForReuse
{
[super prepareForReuse];
cell.btnCheck1.selected = NO;
}

这样每个被重用的单元格都会将它的 btnCheck1.selected 值设置为 NO,当你在 cellForRowAtIndexPath 中加载你的单元格时,它只会在单元格可见并且你将其设置为那个。

但是将所有值存储在 NSMutableArray 中是关键。没有仅将您的值存储在单元格中这样的事情,它们会在无法预见的基础上被重用。将您的值添加到数组并使用 [myArray objectAtIndex:indexPath.row]; 在单元格中打开这些值。

一个例子:

viewDidLoad 中的某处

NSMutableArray *myArray = [[NSMutableArray alloc] initWithObjects:@"1", @"0", @"1", @"1", nil];

在您的cellForRowAtIndexPath

BOOL yesOrNo = [[myArray objectAtIndex:indexPath.row] boolValue];

然后将您的 button.selected 设置为 bool 值。

关于ios - TableView 滚动/dequeueReusableCell 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29007028/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com