使用UITableViewController作为复选框列表时选择默认项目

时间:2009-08-12 16:08:06

标签: iphone uitableview

在很多iPhone应用程序中,我看到一个UITableViewController用作复选框列表。 (有关我的意思,请参阅“设置”下的“自动锁定”)

在尝试自己实现时,我必须跳过很多箍,以便默认以编程方式选择项目(即,列表所代表的当前值)。我能想到的最好的方法是覆盖视图控制器类中的viewDidAppear方法:

- (void)viewDidAppear:(BOOL)animated {
    NSInteger row = 0;

    // loop through my list of items to determine the row matching the current setting
    for (NSString *item in statusItems) {
        if ([item isEqualToString:currentStatus]) {
            break;
        }
        ++row;
    }

    // fetch the array of visible cells, get cell matching my row and set the
    // accessory type
    NSArray *arr = [self.tableView visibleCells];
    NSIndexPath *ip = [self.tableView indexPathForCell:[arr objectAtIndex:row]];
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:ip];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;

    self.lastIndexPath = ip;

    [super viewDidAppear:animated];
}

如果我想默认标记一行,这是获取特定单元格和indexPath引用的最佳/唯一/最简单方法吗?

1 个答案:

答案 0 :(得分:1)

为了显示状态项,无论如何都必须实现tableView:cellForRowAtIndexPath:,不是吗?那么,为什么不在返回单元格之前设置单元格的附件类型,如下所示:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    // dequeue or create cell as usual

    // get the status item (assuming you have a statusItems array, which appears in your sample code)
    NSString* statusItem = [statusItems objectAtIndex:indexPath.row];

    cell.text = statusItem;

    // set the appropriate accessory type
    if([statusItem isEqualToString:currentStatus]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

您的代码非常脆弱,尤其是因为您使用[self.tableView visibleCells]。如果状态项多于屏幕上的行(如名称所示,visibleCells仅返回表视图中当前可见的单元格),该怎么办?