2009-08-12 58 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