2016-12-06 73 views
1

我有當抽頭上呈現出不同的表視圖細胞表視圖刪除單元之後,根據indexPath,即:更新indexPath.row從表視圖

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let nc = UINavigationController() 
    let productController = ProductController() 
    nc.viewControllers = [productController] 

    //Apple 
    if (indexPath.row == 0) { 
     productController.navigationItem.title = "Apple Products"; 
    } 
    //Google 
    if (indexPath.row == 1) { 
     productController.navigationItem.title = "Google Products"; 
    } 
    //Twitter 
    if (indexPath.row == 2) { 
     productController.navigationItem.title = "Twitter Products"; 
    } 
    //Tesla 
    if (indexPath.row == 3) { 
     productController.navigationItem.title = "Tesla Products"; 
    } 
    //Samsung 
    if (indexPath.row == 4) { 
     productController.navigationItem.title = "Samsung Products"; 
    } 
    present(nc, animated: true, completion: nil) 
} 

然而,當我刪除像這樣的細胞....

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) 
{ 
    if editingStyle == .delete 
    { 
     tableView.beginUpdates() 
     CompanyController.companies.remove(at: indexPath.row) 
     CompanyController.logos.remove(at: indexPath.row) 
     tableView.deleteRows(at: [indexPath], with: .fade) 
     tableView.endUpdates() 
    } 
} 

....的indexPath沒有更新,所以如果我刪除了蘋果細胞(在indexPath.row 0),谷歌細胞取代它的位置,但仍領先蘋果產品頁面等等,其他公司也是如此。我想到tableView.delete行的行正在照顧,但事實並非如此。如何刪除某些內容後更新indexPath?

回答

2

不要硬編碼數據並假定具體行。將數據放入數組中,並根據索引路徑從數組中獲取值。當一行被刪除時,通過從數組中刪除來更新您的數據模型。

更新您的didSelectRow方法:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { 
    let nc = UINavigationController() 
    let productController = ProductController() 
    nc.viewControllers = [productController] 

    productController.navigationItem.title = CompanyController.companies[indexPath.row] 
    present(nc, animated: true, completion: nil) 
} 
+0

我的印象是,這是我在做什麼 - 我的數據在陣列(公司徽標)和表使用cell.textLabel填充的.text = CompanyController.companies [indexPath.row]。然後當我刪除時,我使用CompanyController.companies.remove(at:indexPath.row)從數組中刪除。 – d0xi45

+0

但是,您在'didSelectRowAt'方法中硬編碼了字符串和行號。刪除所有這些'if'語句,並使用'productController.navigationItem.title = CompanyController.companies [indexPath.row]'。 – rmaddy

+0

好吧,現在真棒!從來沒有想過這樣做,但它是如此合乎邏輯。真的很感謝幫助! – d0xi45