2012-06-11 224 views
0
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
//case 1 
//The user is selecting the cell which is currently expanded 
//we want to minimize it back 
if(selectedIndex == indexPath.row) 
{ 
    selectedIndex = -1; 
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

    return; 
} 

//case 2 
//First we check if a cell is already expanded. 
//If it is we want to minimize make sure it is reloaded to minimize it back 
if(selectedIndex >= 0) 
{ 
    NSIndexPath *previousPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0]; 
    selectedIndex = indexPath.row; 
    [tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:previousPath] withRowAnimation:UITableViewRowAnimationFade];   
} 


//case 3 
//Finally set the selected index to the new selection and reload it to expand 
selectedIndex = indexPath.row; 
[tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade]; 

} 

請注意案例1和案例2如何關聯collpasing已擴展的行,其中案例3是關於展開未展開的行。UITableViewCell展開和摺疊

展開和摺疊都使用reloadRowsAtIndexPaths函數的相同函數。

這個問題對我來說是一個切換按鈕,當它被展開時,再次運行該函數會崩潰,當它被摺疊時,它會展開?

回答

1

會發生什麼事是,當你調用reloadRowsAtIndexPaths:表視圖將通過調用你的tableView:cellForRowAtIndexPath:實現在UITableViewDataSource重新加載這些行。您需要返回一個單元格,該單元格使用selectedIndex變量來決定它是否應該展開或摺疊(無論您的特定應用程序如何)。它也會在您的UITableViewDelegate上呼叫tableView:heightForRowAtIndexPath:(是的,這很愚蠢,因爲它在委託中),所以如果您的單元格高度發生變化,這個方法也應該根據selectedIndex返回一個值。

另外,我建議你只叫reloadRowsAtIndexPaths:一次,像這樣:

NSMutableArray* rows = [NSMutableArray arrayWithCapacity:2]; 
// Case 2 
if(selectedIndex >= 0) 
{ 
    NSIndexPath* previousPath = [NSIndexPath indexPathForRow:selectedIndex inSection:0]; 
    [rows addObject:previousPath]; 
} 
// Case 3 
selectedIndex = indexPath.row; 
[rows addObject:indexPath]; 
[tableView reloadRowsAtIndexPaths:rows withRowAnimation:UITableViewRowAnimationFade];