1

我是一个iOS新手。我在 UITableView 中使用复选标记,并将选中的值存储在本地数据库中。当我第一次加载应用程序时,我想根据数据库中存在的值设置复选标记的值。我该怎么做?目前这就是我所做的 -

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];
}
if ([indexPath compare:self.lastIndexPath] == NSOrderedSame) 
{
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
} 
else 
{
    cell.accessoryType = UITableViewCellAccessoryNone;
}
// Set up the cell...
NSString *cellValue = [[self countryNames] objectAtIndex:indexPath.row];
cell.textLabel.text = cellValue;

return cell;
}

然后在 didSelectRowAtIndexPath -

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

// some stuff
self.lastIndexPath = indexPath;
[tableView reloadData];
}
4

2 回答 2

3

您是在问如何以及何时设置复选标记,还是在问如何从数据库(例如核心数据)中填充表?

从您的代码中,您代表的唯一数据在[self countryNames]其中,不清楚在什么情况下您希望单元格显示复选标记。不管是什么,只需在为数据配置单元格时检查条件并设置复选标记(在“设置单元格...”注释之后)。

例如,如果您存储用户国家并检查该单元格:

// get the current country name
NSString *cellValue = [[self countryNames] objectAtIndex:indexPath.row];

// configure the cell
cell.textLLabel.text = cellValue;
UITableViewCellAccessoryType accessory = UITableViewCellAccessoryNone;
if ([cellValue isEqualToString:self.usersCountry]) {
    accessory = UITableViewCellAccessoryCheckmark;
}
cell.accessoryType = accessory;
于 2011-11-07T23:25:04.613 回答
0

如果您有静态表格数据,那么您只需要存储所选表格视图单元格的部分和行。如果您有动态数据,则需要将所选单元格的唯一数据存储在数据库中,并将其与加载时单元格的内容进行比较。当您将单元格加载到 中时cellForRowAtIndexPath:,只需将该单元格的附件设置UITableViewCellAccessoryCheckmark为以及设置self.lastIndexPath = indexPath为稍后进行比较。

另外,我通常使用[indexPath isEqual:self.lastIndexPath]而不是compare:. 无论哪种方式都没有真正的区别,只是为了可读性。

于 2011-11-07T23:23:31.467 回答