如何在待办事项列表中划分部分

问题描述 投票:0回答:1

我正在使用 diffable 数据源在 Swift 中执行待办事项。

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

enter image description here

我不记得他们尝试了多少次。他们有足够多的人告诉我使用两个数组。

ios swift uitableview uikit uitableviewdiffabledatasource
1个回答
0
投票

试试这个:

//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
    })
}
© www.soinside.com 2019 - 2024. All rights reserved.