2016-03-15 65 views
0

我爲這個措辭不佳的問題表示歉意,但我根本無法想象爲什麼/如何以短的方式描述此錯誤。自定義的UITableviewCells顯示正確,但只有一個在該部分是正確的類

基本上我有一個表視圖控制器顯示兩個部分,每個都有一個相應的自定義UITableViewCell子類。它們顯示完美,具有正確的模型數據。

當我點擊「完成」按鈕時,出現問題,我的程序遍歷所有單元格,從每個單元格收集數據並更新模型。第一部分沒有阻礙,但第二部分是麻煩隱藏的地方。本節的第一個單元格可以被轉換爲正確的子類,但是任何其他附加單元格都不會通過此條件測試,並且它們的重用標識符爲零。我嘗試檢查出現的單元格,但它們正在被正確創建/重用。我的代碼如下,任何建議都將有助於我的理智。

這裏是穿越細胞我的助手功能的一部分:

for i in 0..<tableView.numberOfSections { 
     for j in 0...tableView.numberOfRowsInSection(i) { 
      let cell = tableView.cellForRowAtIndexPath(NSIndexPath(forRow: j, inSection: i)) 

       // This section seems to work fine 
       if(i == 0){ 
        if let gradeCell: PercentTableViewCell = cell as? PercentTableViewCell { 
         print("retrieveCellInfo: gradeCell - \(gradeCell.getPercent())") 
         newPercentages.append(gradeCell.getPercent()) 
        } 
       } else if (i == 1){ 
        print("Else if i == 1 : j == \(j) : \(cell?.reuseIdentifier!)") // Prints "category" for the first cell and "nil" for any other 

        // This is the cast conditional that only lets one cell through 
        if let catCell = cell as? EditTableViewCell{ 
         newCategories.append(Category(name: catCell.category!, weight: catCell.weight!, earned: catCell.earned!, total: catCell.total!)) 
        } 
       } 
     } 
    } 

這裏是我的委託功能,完美據我可以告訴工作。正如我所說的,是正確顯示UI:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 

    if(indexPath.section == 0){ 
     /* Grade Parameter Cells */ 
     let cell: PercentTableViewCell = tableView.dequeueReusableCellWithIdentifier("gradeParam", forIndexPath: indexPath) as! PercentTableViewCell 

     var gradePercentages = course?.getGradePercentages() 

     // Make sure percentages array is sorted correctly 
     gradePercentages?.sortInPlace() { 
      return $0 > $1 
     } 

     // Update cell's member variables 
     cell.initialize(letters[indexPath.row], percent: gradePercentages![indexPath.row]) 

     return cell 

    } else { 
     /* Category Cells */ 
     let catcell: EditTableViewCell = tableView.dequeueReusableCellWithIdentifier("category", forIndexPath: indexPath) as! EditTableViewCell 

     let category = categories![indexPath.row] 

     catcell.setLabels(category.name, earned: category.earned, total: category.total, weight: category.weight) 

     return catcell 
    } 
} 
+1

你正在走錯這個方向。您不應該嘗試維護單元格內的狀態,因爲它將被重用 - 您可能有20行,但實際上只有8個單元格可能存在。相反,您需要將這種狀態保持在單元之外,並在需要時將其顯示在單元中。同樣,當單元格中的「gradePercentage」字段已更新時,它應更新此狀態。 – Michael

回答

1

的問題出現了,當我點擊「完成」按鈕,我的程序遍歷 通過所有的細胞,每個細胞採集數據和更新 的模型

這是你的問題。你的單元格應該反映你的數據模型,它們不能被依賴來保存數據,因爲一旦單元格離屏,它可能被重新用於屏幕上的一行。

如果數據由用戶與單元格交互進行更新,那麼您應該更新您的數據模型。如果您不想立即提交更改,則可以使用臨時存儲。

相關問題