2016-09-28 64 views
0

我有一個從API調用填充的數組。我用這個陣列中填充表視圖這樣:在我穿過陣列中的藥物對象的細胞滾動時在UITableView上保持按鈕狀態

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCellWithIdentifier(cellReuseIdendifier, forIndexPath: indexPath) as! MBTableViewCell 

     cell.cellText = morningArray[indexPath.row].name 
     cell.cellImage = (DosageTypes(rawValue: morningArray[indexPath.row].measurement)?.image)! 
     cell.cellDossage = "\(morningArray[indexPath.row].dosage) \(DosageTypes(rawValue: morningArray[indexPath.row].measurement)!.description)" 
     cell.pointsButton.medication = morningArray[indexPath.row] 
     return cell 
} 

pointsButton。 pointsButton根據對象的狀態改變狀態。 pointButton也可以改變它自己的狀態。風格根據狀態而變化。這裏是在各點按鈕的代碼:

private var _medication :MBMedicationTaken? 
    var medication : MBMedicationTaken? { 
    set{ 
     self._medication = newValue 
     if self._medication!.taken == false{ 
     setNotTaken() 
     } else { 
     setTaken() 
     } 
    } 
    get{ 
     return self._medication 
    } 
    } 

當我滾動,的點按鈕的值發生變化,因爲它連續地通過在陣列中的舊值發送。我怎樣才能讓它滾動時的值不會改變?把它看作與Twitter收藏夾按鈕相似。

回答

0

,因爲它不斷通過舊值發送陣列

發生這種情況,當你加載數據到第一負載填充您的UITableView英寸它不再更新 - 所以當你滾動時,UITableView使用初始數據集中的值。

你應該做到以下幾點:

據我瞭解,該pointsButton是一個的UIButton,可以有2個不同的狀態?要麼?如果是的話,你應該:

  1. 當按下任何按鈕添加功能:

    cell.pointsButton.addTarget(self, action: #selector(self.buttonAction(sender:)), 
           for: UIControlEvents.touchUpInside) 
    cell.pointsButton.tag = indexPath.row // add an unique identifier 
    
  2. 添加一個按鈕動作,在按下一個按鈕,用於檢測

    func buttonAction(sender:UIButton!) { 
    
        let index = sender as! Int 
        // with this index, you know the correct index in your morningArray 
    
        // check if any value (i dont know how your object look like, for example ill use any Bool Value) 
    
        // change state 
    
        if(morningArray[index].selected == true) { 
         morningArray[index].selected = false 
        } else { 
         morningArray[index].selected = true 
        } 
    
    } 
    
  3. 現在,當您登記cellForRowAtIndexPath時,該州的值應該是正確的。

    if(morningArray[indexPath.row].selected == true) { 
         // activate State Button 
        } else { 
         // disable State Button 
        } 
    
+0

這會工作,但有2種不同的數據源,感覺就像是一種黑客的誠實。有什麼意見? – spogebob92

+0

請提供更多的代碼,然後;) – derdida

+0

@derdida是正確的。你需要跟蹤某個地方的狀態;一個細胞只是一個觀點。它不存儲自己的信息。你需要擴展現有的模型對象來存儲這些信息或使用輔助數據結構,但如果你這樣做,那麼我會建議一個NSMutableIndexSet而不是一個數組 – Paulw11

相關問題