我在从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])
}
答案 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])
}