我正在尝试在每个 uitableviewcell 中创建一个复选框,可以在选中和未选中之间切换。为了确保加载新单元格时单个选择不会循环,我创建了一个可变的字符串数组来表示“取消选中”或“选中”(即当按钮图像应该显示为未选中或选中时)。按下检查按钮时,字符串将替换为“检查”或“取消检查”。由于某种我看不到的原因,当 tableview 滚动并且带有选定检查按钮的单元格离开屏幕时,数组会丢失对其所做的更改,因此检查字符串会丢失。
有什么想法有什么问题吗?
在此先感谢您的帮助。
在“checkButtonClicked”中检查了第一个单元格中的按钮之后的 selectedCheckArray 的 NSLog:{ Check, Uncheck, Uncheck, Uncheck, Uncheck, Uncheck, Uncheck }
向下滚动后,selectedCheckArray 的 NSLog 使第一个单元格不再出现在屏幕上:{ Uncheck, Uncheck, Uncheck, Uncheck, Uncheck, Uncheck, Uncheck }
这是代码:
。H
@property (strong, nonatomic) NSMutableArray *selectedCheckArray;
.m
@synthesize selectedCheckArray;
...
- (void)viewWillAppear:(BOOL)animated
{
// cellDataArray loaded here
selectedCheckArray = [[NSMutableArray alloc] init];
for (int i = 0; i<[cellDataArray count]; i++) {
[selectedCheckArray addObject:@"Uncheck"];
}
[super viewWillAppear:animated];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [cellDataArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"choiceCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
UIButton *checkButton = (UIButton *)[cell viewWithTag:1];
if ([[selectedCheckArray objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"]) {
[checkButton setImage:[UIImage imageNamed:@"unchecked"]
forState:UIControlStateNormal];
} else {
[checkButton setImage:[UIImage imageNamed:@"checked"]
forState:UIControlStateNormal];
}
[checkButton addTarget:self action:@selector(checkButtonClicked:)
forControlEvents:UIControlEventTouchUpInside];
return cell;
}
...
- (void)checkButtonClicked:(id)sender
{
// indexPath of cell of clicked button
CGPoint touchPoint = [sender convertPoint:CGPointZero toView:choiceTable];
NSIndexPath *indexPath = [choiceTable indexPathForRowAtPoint:touchPoint];
// Not using tag as sender will keep reference of clicked button
UIButton *button = (UIButton *)sender;
//Checking the condition button is checked or unchecked.
//accordingly replace the array object and change the button image
if([[selectedCheckArray objectAtIndex:indexPath.row] isEqualToString:@"Uncheck"])
{
[button setImage:[UIImage imageNamed:@"checked"] forState:UIControlStateNormal];
[selectedCheckArray replaceObjectAtIndex:indexPath.row withObject:@"Check"];
} else {
[button setImage:[UIImage imageNamed:@"unchecked"] forState:UIControlStateNormal];
[selectedCheckArray replaceObjectAtIndex:indexPath.row withObject:@"Uncheck"];
}
}