1

好的,我有一个带有可区分数据源的集合视图的初步工作版本。一切正常,我刚刚实现了添加和更改项目,以及删除仍有待完成的项目。目前关于使用可区分数据源添加、更改和删除项目的信息很少。我想知道我做的所有数组的东西是否都是正确的方法。我觉得我应该对快照做更多的事情。保存方法中的所有逻辑都应该在更新方法中吗?任何帮助表示赞赏和/或有关此事的任何资源

ProjectsViewController: UIViewController {
(...)
    //DataSource methods (snapshot)
    func updateData(on projects: [Project]) {
        var snapshot = NSDiffableDataSourceSnapshot<Section, Project>()
        snapshot.appendSections([Section.normal])
        snapshot.appendItems(projects)

        //apply() is safe to call from a background queue!
        self.dataSource.apply(snapshot, animatingDifferences: true)
    }

(...)
}

//MARK: - ProjectHandler (delegation method)
extension ProjectsViewController: ProjectHandler {
    func save(_ project: Project, withImage image: UIImage?) {
        //Make sure LastEdited Date gets updated
        var projectToBeSaved = project
        projectToBeSaved.lastEdited = Date()

        //Current state
        var projects = dataSource.snapshot().itemIdentifiers

        //Replace the changed project
        if projects.contains(projectToBeSaved) {
            let index = projects.firstIndex(of: projectToBeSaved)
            projects.remove(at: index!)
            projects.append(projectToBeSaved)
        //Add the new projects
        } else {
            projects.append(projectToBeSaved)
        }

        //sort on lastly edited
        projects.sort { $0.lastEdited > $1.lastEdited }

        //TODO: - Write to json

        //update the snapshot
        updateData(on: projects)
        collectionView.reloadData()
    }
}

4

0 回答 0