UITableViewCellはスクロールされて画面から見えなくなると、これから見える別のCellとして再利用されてしまいます。その際にチェックをつけたという情報はなくなってしまいます。
そのため何番目のCellがチェックされているかという情報を別途保存しておき、そのCellが再び見えるようになるときにCheckをつけてやるという処理が必要です。
なので
どこかにindexを保存しておくarrayを作っておき
ObjectiveC
1@interface ViewController ()
2
3// 選択されたcellのindexPath.rowを保存しておくarray
4@property (nonatomic, readwrite) NSMutableArray *array;
5
6@end
didSelectRowAtIndexPath
で選択されたCellのindexを覚えておきます。
ObjectiveC
1- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
2
3 UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
4
5 // checkmarkがなかったらcheckmarkつけてarrayに保存
6 if (cell.accessoryType == UITableViewCellAccessoryNone) {
7 cell.accessoryType = UITableViewCellAccessoryCheckmark;
8 [self.array addObject:@(indexPath.row)];
9 } else {
10 // checkmarkがあったらcheckmark外してarrayから削除
11 cell.accessoryType = UITableViewCellAccessoryNone;
12 [self.array removeObject:@(indexPath.row)];
13 }
14 [tableView reloadData];
15}
そしてCellが再描画されるときにcheckをつけたCellのindexだったらチェックをつける
ObjectiveC
1- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
2
3 static NSString *CellIdentifier = @"Cell";
4 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
5 if (cell == nil) {
6 cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
7 cell.selectionStyle = UITableViewCellSelectionStyleNone;
8 }
9
10 // arrayにindexが保存してあったらcheckmarkつける
11 if (self.array && [self.array containsObject:@(indexPath.row)]) {
12 cell.accessoryType = UITableViewCellAccessoryCheckmark;
13 } else {
14 cell.accessoryType = UITableViewCellAccessoryNone;
15 }
16 cell.textLabel.text = [NSString stringWithFormat:@"%ld", (long)indexPath.row];
17 return cell;
18
19}
のようにすればスクロールしてもチェックマークはついたままになるはずです。
もしかしたら下記はそれを意図した処理だったのかもしれませんが、判定にミスっていて常にUITableViewCellAccessoryNoneの処理を通っているためチェックが消えてしまったのではないかと思います。
ObjectiveC
1if ([[array objectAtIndex:indexPath.row] isEqualToString:cell]) {
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2015/09/02 02:55
2015/09/04 16:52
2015/09/11 00:10