ios - dataSource 不会在 cellForItemAt 函数中更新

标签 ios swift uicollectionview

我在从我的 cellForItemAt 获取更新数据源时遇到问题。

    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
}

当用户点击复选框按钮时,buttonTapped 函数将被调用并通过协议(protocol)传递数据。

    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])
}

最佳答案

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])
}

关于ios - dataSource 不会在 cellForItemAt 函数中更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46064396/

相关文章:

ios - Swift:基于奇数项或偶数项的 2 列网格中的 UICollectionView 动态单元格大小

ios - UITableViewController 类似于 iOS7 日历应用程序的添加事件 TableView Controller

iOS CAEmitterCell烟花效果

ios - `tableView:heightForHeaderInSection:` 调用了未实现它的委托(delegate)

ios - 始终(强制)输入小写或大写 - iOS swift

ios - 带有较长标签的标签 ListView 未在 iOS swift 中完全显示

ios - 如何获取当前弹出键盘的类型

ios - 解雇 AVPlayerViewController 不会 'kill' 对象 - 它会持续存在

ios - 可扩展的 UICollectionViewCell

ios - CollectionView - fatal error : index out of range - More cells than the view can show