dataSource不会在cellForItemAt函数中更新

时间:2017-09-05 22:53:59

标签: ios swift uicollectionview

我在从cellForItemAt获取更新的dataSource时遇到问题。

    override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! QuestLogCollectionViewCell
    cell.delegate = self
    let task = board[indexPath.section].tasks[indexPath.row]
    cell.task = task
    cell.taskLabel.text = task.action
    cell.ifTaskCompleted = task.ifTaskComplete
    return cell
}

当用户点击checkBox按钮时,将调用buttonTapped函数并通过协议传递数据。

    func buttonTapped() {
    guard let taskStatus = ifTaskCompleted else {return}
    if taskStatus == true {
        checkBoxButton.setImage(#imageLiteral(resourceName: "box"), for: .normal)
    } else {
        checkBoxButton.setImage(#imageLiteral(resourceName: "checkedBox"), for: .normal)
    }
    delegate?.userMarkedTaskCompleted(ifTaskComplete: !taskStatus, for: self)
}

    func userMarkedTaskCompleted(ifTaskComplete: Bool, for cell: QuestLogCollectionViewCell) {
    guard let indexPath = self.collectionView?.indexPath(for: cell) else {return}
    var tasks = board[indexPath.section].tasks
    tasks[indexPath.row].ifTaskComplete = ifTaskComplete
    collectionView?.reloadItems(at: [indexPath])
}

1 个答案:

答案 0 :(得分:1)

var tasks = board[indexPath.section].tasks可能会有问题。具体来说,如果您的任务类型是值类型(例如struct类型),那么您可以更新原始结构的副本。

我建议您直接更新board / tasks结构:

func userMarkedTaskCompleted(ifTaskComplete: Bool, for cell: QuestLogCollectionViewCell) {
    guard let indexPath = self.collectionView?.indexPath(for: cell) else {return}
    board[indexPath.section].tasks[indexPath.row].ifTaskComplete = ifTaskComplete
    collectionView?.reloadItems(at: [indexPath])
}