2012-11-20 21 views
0

我有一個具有可擴展單元的UItable。 當用戶點擊某個部分時,它將展開並顯示這些行。但是我需要在新部分打開之前關閉以前打開的部分。我想我需要在didselectrow中做到這一點,只是不知道該怎麼做?關閉UITable的所有部分

我對didselectrow代碼如下

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    if(tableView.tag == 4) 
    { 
     //NSLog(@"Did Select Row"); 

     if ([self tableView:tableView canCollapseSection:indexPath.section]) 
     { 
      if (!indexPath.row) 
      { 
       // only first row toggles exapand/collapse 
       [tableView deselectRowAtIndexPath:indexPath animated:YES]; 

       NSInteger section = indexPath.section; 
       BOOL currentlyExpanded = [expandedSections3 containsIndex:section]; 
       NSInteger rows; 


       NSMutableArray *tmpArray = [NSMutableArray array]; 

       if (currentlyExpanded) 
       { 
        rows = [self tableView:tableView numberOfRowsInSection:section]; 
        [expandedSections3 removeIndex:section]; 

       } 
       else 
       { 
        [expandedSections3 addIndex:section]; 
        rows = [self tableView:tableView numberOfRowsInSection:section]; 
       } 


       for (int i=1; i<rows; i++) 
       { 
        NSIndexPath *tmpIndexPath = [NSIndexPath indexPathForRow:i 
                   inSection:section]; 
        [tmpArray addObject:tmpIndexPath]; 
       } 

       //UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; 

       if (currentlyExpanded) 
       { 
        [tableView deleteRowsAtIndexPaths:tmpArray 
           withRowAnimation:UITableViewRowAnimationTop]; 

       } 
       else 
       { 
        [tableView insertRowsAtIndexPaths:tmpArray 
           withRowAnimation:UITableViewRowAnimationTop]; 
       } 
      } 

      else { 

      } 
     } 

     //NSLog(@"Button Pressed?"); 
    } 
} 

回答

0

嘗試調用的UITableView的reloadSections:withRowAnimation:tableView:didSelectRowAtIndexPath:內。這可以讓表格視圖爲您指定的部分重新查詢您的委託。作爲一個好處,您將獲得一個很好的動畫,以便以這種方式添加和刪除行。

當然,這與您當前直接操縱表視圖行的解決方案完全不同,所以如果您想嘗試reloadSections:withRowAnimation:,您可能需要重寫委託的重要部分。這些更改將涉及將部分的摺疊/展開狀態直接存儲在委託或由委託引用的模型對象中,以便委託在被表視圖重新查詢時具有更新的返回值。

+0

嗨,有沒有任何教程,你知道這可能能夠幫助我的建議? –

+0

@hanimal_p:不,我沒有任何特定的教程。我會推薦學習Apple的UITableView文檔,特別是關於各種重載方法的部分。然後是Apple的[Table View Programming Guide](表格編程指南)(http://developer.apple.com/library/ios/#documentation/UserExperience/Conceptual/TableView_iPhone/AboutTableViewsiPhone/AboutTableViewsiPhone.html),最後我會求助於[googling] (https://www.google.ch/search?q=uitableview+tutorial+reloaddata)。如果您對「狀態保存」或「模型對象」部分感到困惑,我建議查看MVC設計模式。 – herzbube