0

我遇到了以下代码的问题,它应该只允许选择一个表格行并显示一个复选标记。目前,行中显示了多个复选标记。

谢谢你的帮助

- (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;
  }
4

1 回答 1

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;

}
于 2013-01-28T14:15:04.987 回答