選択済みと未選択を切り替えることができるチェックボックスを各uitableviewcellに作成しようとしています。新しいセルをロードするときに単一の選択がリサイクルされないようにするために、「チェックを外す」または「チェックする」(つまり、ボタンの画像がチェックされていないかチェックされている場合)を示す文字列の可変配列を作成しました。チェックボタンを押すと、文字列が「チェック」または「チェック解除」に置き換えられます。なんらかの理由で、テーブルビューがスクロールし、選択したチェックボタンのあるセルが画面外に出ると、配列に加えられた変更が失われるため、チェック文字列が失われます。
何が問題なのですか?
助けてくれてありがとう。
最初のセルのボタンが「checkButtonClicked」でチェックされた直後のselectedCheckArrayのNSLog:{チェック、チェック解除、チェック解除、チェック解除、チェック解除、チェック解除、チェック解除}
下にスクロールして最初のセルが画面に表示されなくなった後の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"];
}
}