swift 如何在待办事项列表中创建节

2ic8powd  于 2023-11-16  发布在  Swift
关注(0)|答案(1)|浏览(124)

我在Swift中使用了diffable数据源。

private var todos = [[ToDoItem]]() // my dataSource 
enum Section { // my sections 
    case unfulfilled
    case completed
}

字符串
通过点击任务上的淘汰,任务本身应该从未完成部分移动到已完成部分。
我还被告知要对两个数组使用该方法。
也就是说,我有我通常的任务,todo将到达哪里,告诉我如何确保我有第二个分支负责第二部分,或者如何解决这个问题。
我的旧代码的一个例子:

func configureSnapshot() {
    var snapshot = Snapshot()
    
    if todos.isEmpty { return }
    if todos.count == 1 {
        if todos.first!.first!.isCompleted {
            snapshot.appendSections([.completed])
            snapshot.appendItems(todos.first!, toSection: .completed)
        } else {
            snapshot.appendSections([.unfulfilled])
            snapshot.appendItems(todos.first!, toSection: .unfulfilled)
        }
        
    } else if todos.count == 2 {
        snapshot.appendSections([.unfulfilled, .completed])
        snapshot.appendItems(todos.first!, toSection: .unfulfilled)
        snapshot.appendItems(todos[1], toSection: .completed)
    }
    
    dataSource?.apply(snapshot, animatingDifferences: true)
}


的数据
我已经记不清他们尝试了多少次了,但已经足够让我用两个法阵了。

niknxzdl

niknxzdl1#

试试这个:

//backing data source
private var unfulfilledToDos = [ToDoItem]()
private var completedToDos = [ToDoItem]()

//To-do sections
enum ToDoSection: Int, CaseIterable {
    case unfulfilled
    case completed
}

/// call this when you want tableview/collectionview to reload data
func reloadData(shouldAnimate: Bool) {
    var snapshot = NSDiffableDataSourceSnapshot<ToDoSection, ToDoItem>()
    //if you have no data for that section, tableview/collectionview will create the section with 0 height - thereby rendering the section invisible
    //however, if you have content insets on that section, it will still create those content insets on a section that is not visible. if this doesn't work for your UX, then simply don't append that section below
    snapshot.appendSections(ToDoSection.allCases) 

    ToDoSection.allCases.forEach { eachSection in
        switch eachSection {
        case .unfulfilled:
            snapshot.appendItems(unfulfilledToDos, toSection: eachSection)
        case .completed:
            snapshot.appendItems(completedToDos, toSection: eachSection)
        }
    }

    dataSource?.apply(snapshot, animatingDifferences: shouldAnimate, completion: { [weak self] in
        //reload of data is completed
    })
}

字符串

相关问题