2015-09-23 36 views
0

didSelectRowAtIndexPath我的表視圖控制器的方法出於某種原因,我應該打電話給我的表視圖reloadData。在此之後,任何選擇都將消失。哪種方法可以保留表格的選擇?如何在didSelectRowAtIndexPath的表視圖中重新加載數據並保留選擇?

UPD:我試圖做selectRowAtIndexPath後,我重新加載表didSelectRowAtIndexPath,但它沒有導致任何結果,選擇仍然失蹤。但它會工作,如果我會在dispatch_after區塊,雖然這是一個非常奇怪的解決方案。我需要以正確的方式去做。

+0

只是得到一個布爾標誌並存儲前一行索引,並且在重載表格視圖時比checkfor cellforrowatindexpath檢查行並檢查布爾標誌,並且如果它被選中,而不是做任何你想做的事並設置'[cell setSelected: YES]'和其他'[cell setSelected:NO]' –

回答

0

重新加載發生在下一個佈局過程中,這通常發生在將控制權返回到運行循環(在您的按鈕操作或任何返回之後)之後。

所以運行表視圖重裝後的東西的一種方式是簡單地強制表視圖立即進行佈局:

- (void)reloadTableView 
{ 
    NSArray *indexPaths = [self.tableView indexPathsForSelectedRows]; 
    [self.tableView reloadData]; 
    [self.tableView layoutIfNeeded]; 
    for (NSIndexPath *path in indexPaths) { 
     [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone]; 
    } 
} 

或者就像你說的,你可以使用GCD來安排你的後佈局代碼後來運行

- (void)reloadTableView 
{ 
    NSArray *indexPaths = [self.tableView indexPathsForSelectedRows]; 
    [self.tableView reloadData]; 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     for (NSIndexPath *path in indexPaths) { 
     [self.tableView selectRowAtIndexPath:path animated:NO scrollPosition:UITableViewScrollPositionNone]; 
     } 
    } 
} 
+0

更新了我的回答 – Istvan

+0

嗯,沒有幫助,我用你的兩個方法... – surfrider

0

添加-selectRowAtIndexPathanimated標誌設置爲NO你叫[tableView reloadData]-didSelectRowAtIndexPath後。

的Objective-C:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    ... 
    [tableView reloadData]; 
    [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone]; 
    ... 
} 

斯威夫特:

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { 
    ... 
    tableView.reloadData() 
    tableView.selectRowAtIndexPath(indexPath, animated: false, scrollPosition: .None) 
    ... 
} 
+0

正如我評論Istvan的答案,它不適合我,這種情況下不會出現選擇。 – surfrider

0

可以使用。

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

    [tableView deselectRowAtIndexPath:indexPath animated:YES]; 
    //add you code and reload the table 

} 
0

在 「didSelectRowAtIndexPath方法」 委託方法,請參考你的選擇indexPath的:

indexPathReference = indexPath; 

和重裝表視圖後,加入這行:

[tableView selectRowAtIndexPath:indexPathReference animated:NO scrollPosition:UITableViewScrollPositionNone]; 
0

didSelectRowAtIndexPath你必須保持對所選indexPath的引用。 那麼你應該叫reloadData

reloadData將觸發調用cellForRowAtIndexPath:

這就是你檢查各項指標與您的存儲indexPath和所選設置單元。 (cell.selected = true

相關問題