2013-10-25 97 views
-2

我有一個tableview控制器,我希望能夠一次選擇2個,並且只有2個單元格。如果您已經檢查了2個單元格並且點擊另一個未選中的單元格,則第1個單元格將取消選中,並且現在將檢查最近的2個單元格。下面是我在用失敗:有趣的循環行爲?

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

     int count = 0; 
    int i = 0; 

    NSIndexPath *datPath = 0; 
    for (UITableViewCell *cell in [self.tableView visibleCells]) { 
     i++; 
     datPath = [NSIndexPath indexPathForRow:i inSection:0]; 
     if([tableView cellForRowAtIndexPath:datPath].accessoryType == UITableViewCellAccessoryCheckmark){ 
     count++; 
     } 
    } 

    if(count == 0){ 
     firstChecked = indexPath; 
     [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark; 
     [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; 
    } 

    if(count == 1){ 
     secondChecked = indexPath; 
     [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark; 
     [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; 
    } 

    if(count == 2){ 
     [tableView cellForRowAtIndexPath:firstChecked].accessoryType = UITableViewCellAccessoryCheckmark; 
     firstChecked = secondChecked; 
     secondChecked = indexPath; 
     [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark; 
     [self.tableView deselectRowAtIndexPath:indexPath animated:YES]; 
    } 

    NSLog(@"Count is equal to: %d",count); 

對於那些想知道,我有讓我的表視圖多重選擇。以上代碼會發生什麼情況如下。伯爵不值錢,所以我可以檢查3次,然後停下來讓我檢查。我錯過了什麼嗎?謝謝。

+0

當你有兩個已經選擇你不取消設置附件類型;你再次設置它'[tableView cellForRowAtIndexPath:firstChecked] .accessoryType = UITableViewCellAccessoryCheckmark;' –

回答

2

您隨時檢查裏面的for循環(indexPath是您當前選擇的小區)相同的細胞: if([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryCheckmark)