2009-08-12 51 views
0

在很多iPhone应用程序中,我看到一个UITableViewController被用作复选框列表。 (例如,我的意思是,在设置下的自动锁定的例子)使用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

为了显示状态项目,您必须实施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仅返回表格视图的当前可见单元格),该怎么办?

+0

看,我觉得我是愚蠢的代码。今天缓慢的大脑:P – Dana 2009-08-12 19:14:15