我遇到以下代码的问题,应该只允许选择一个表行并显示复选标记。目前,行中显示多个复选标记。
感谢您的帮助
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//Save the row selected to nsuserdefaults
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:cell.textLabel.text forKey:@"countrySaved"];
if (cell.accessoryType == UITableViewCellAccessoryNone)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
UIImage *image = [UIImage imageNamed:@"icon-tick.png"];
UIButton *checkmarkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[checkmarkBtn setImage:image forState:UIControlStateNormal];
[checkmarkBtn setFrame:CGRectMake(0, 0, 19, 19)];
[checkmarkBtn setBackgroundColor:[UIColor clearColor]];
[self.tableView cellForRowAtIndexPath:indexPath].accessoryView = checkmarkBtn;
} else
{
cell.accessoryType = UITableViewCellAccessoryNone;
UIButton *checkmarkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[checkmarkBtn setTitle:@"" forState:UIControlStateNormal];
[checkmarkBtn setFrame:CGRectMake(0, 0, 0, 0)];
[self.tableView cellForRowAtIndexPath:indexPath].accessoryView = checkmarkBtn;
}
}
我在一些帖子中看到我必须包含以下内容,但我不确定如何在代码中实现它。
cell.accessoryType = UITableViewAccessoryNone;
if (indexPath.row == index) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
答案 0 :(得分:0)
只需查看此代码:
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
//Save the row selected to nsuserdefaults
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:cell.textLabel.text forKey:@"countrySaved"];
[prefs setObject:[NSNumber numberWithInt:indexPath.row] forKey:@"selectedRow"];
[tableView reloadData];
}
在cellForRowAtIndexPath中:
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
int val = [[prefs objectForKey:@"selectedRow"] intValue];
if (indexPath.row == val)
{
cell.accessoryType = UITableViewCellAccessoryCheckmark;
UIImage *image = [UIImage imageNamed:@"icon-tick.png"];
UIButton *checkmarkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[checkmarkBtn setImage:image forState:UIControlStateNormal];
[checkmarkBtn setFrame:CGRectMake(0, 0, 19, 19)];
[checkmarkBtn setBackgroundColor:[UIColor clearColor]];
[self.tableView cellForRowAtIndexPath:indexPath].accessoryView = checkmarkBtn;
} else
{
cell.accessoryType = UITableViewCellAccessoryNone;
UIButton *checkmarkBtn = [UIButton buttonWithType:UIButtonTypeCustom];
[checkmarkBtn setTitle:@"" forState:UIControlStateNormal];
[checkmarkBtn setFrame:CGRectMake(0, 0, 0, 0)];
[self.tableView cellForRowAtIndexPath:indexPath].accessoryView = checkmarkBtn;
}