我有一个 UITableView,它在选择一行时显示复选标记。问题是当表格视图滚动时,当只选择一个行时会显示多个复选标记。当表格滚动和出队过程发生时,问题就出现了。这是我的 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];
}