行が選択されたときにチェックマークを表示するUITableViewがあります。問題は、テーブルビューがスクロールすると、行が1つだけ選択されたときに、複数のチェックマークが表示されることです。この問題は、テーブルがスクロールし、デキュープロセスが発生するときに発生します。これが私のcellForRowAtIndexPathです:メソッド
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MainCell"];
if(cell == nil){
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"MainCell"];
cell.selectedBackgroundView = [[UIView alloc] initWithFrame:CGRectZero];
cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:204.0/255.0 green:56.0/255.0 blue:55.0/255.0 alpha:1];
}
// Get item from tableData
NSDictionary *item = (NSDictionary *)[displayItems objectAtIndex:indexPath.row];
cell.textLabel.text = [item objectForKey:@"key"];
[cell.textLabel setFont:[UIFont fontWithName: @"Asap-Bold" size: 14.0f]];
return cell;
}
およびdidSelectメソッド:
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
selectedCityTableString = cell.textLabel.text;
cellAccessoryImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-tick.png"]] ;
cellAccessoryNoneImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@""]] ;
if (cell.accessoryType==UITableViewCellAccessoryNone)
{
// cell.accessoryType=UITableViewCellAccessoryCheckmark;
cell.accessoryView = cellAccessoryImageView;
if (prev!=indexPath.row) {
cell=[tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:prev inSection:0]];
//cell.accessoryType=UITableViewCellAccessoryNone;
cell.accessoryView = cellAccessoryNoneImageView;
prev=indexPath.row;
}
}
else{
// cell.accessoryType=UITableViewCellAccessoryNone;
cell.accessoryView = cellAccessoryNoneImageView;
}
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSString *mutCityStr = [[selectedCityTableString stringByReplacingOccurrencesOfString:@" " withString:@"+"] lowercaseString];
// NSString *mutCityStr = @"c";
[prefs setObject:mutCityStr forKey:@"selectedCityTableString"];
[prefs synchronize];
#ifdef DEBUG
NSLog(@"mutCityStr is %@",mutCityStr);
NSLog(@"selectedCityTableString is %@",selectedCityTableString);
NSLog(@"posting notification from TWO TABLES");
#endif
[[NSNotificationCenter defaultCenter] postNotificationName:@"TTSelectedList" object:selectedCountryTableString];
}