2016-09-28 66 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

相关问题