swift 在NSCollectionViewDiffableDataSource中追加节

pjngdqdw  于 2022-10-31  发布在  Swift
关注(0)|答案(4)|浏览(168)

我尝试使用NSCollectionViewDiffableDataSourceNSCollectionViewCompositionalLayout创建一个包含动态节数的NSCollectionView
集合视图用于显示搜索结果,节的数量取决于找到的结果的类型和数量。每个节使用不同的布局显示其内容类型。
数据源声明为NSCollectionViewDiffableDataSource<String, SearchResult>,其中SearchResult是使用UUID()实现Hashable的类。具有零结果的节不是空的,而是它们不存在于集合视图中。
当显示我的视图控制器时,我清除了现有的搜索结果:

func clearSearchResults(animate: Bool) {
    let snapshot = NSDiffableDataSourceSnapshot<String, SearchResult>()
    dataSource.apply(snapshot, animatingDifferences: animate)
}

在执行搜索时,我尝试为找到的每种类型的结果在集合视图中添加一个部分:

// Code that performs the search
var snapshot = NSDiffableDataSourceSnapshot<String, SearchResult>()

// If I append more than one section an exception is thrown in apply():
// snapshot.appendSections([ViewController.trackSection, ViewController.albumSection])

snapshot.appendSections([ViewController.trackSection])
snapshot.appendItems(tracks, toSection: ViewController.trackSection)

// This also causes an exception in apply():
// snapshot.appendSections([ViewController.albumSection])
// snapshot.appendItems(albums, toSection: ViewController.albumSection)

dataSource.apply(snapshot, animatingDifferences: true)

堆栈跟踪为:

2019-11-10 13:34:29.883728-0600 DiffableTest[64931:1820050] [General] An uncaught exception was raised
2019-11-10 13:34:29.883813-0600 DiffableTest[64931:1820050] [General] -[NSCollectionView insertSections:] Section index 1 out of bounds
2019-11-10 13:34:29.883937-0600 DiffableTest[64931:1820050] [General] (
    0   CoreFoundation                      0x00007fff33a98f53 __exceptionPreprocess + 250
    1   libobjc.A.dylib                     0x00007fff69b5e835 objc_exception_throw + 48
    2   CoreFoundation                      0x00007fff33a98da9 +[NSException raise:format:] + 189
    3   UIFoundation                        0x00007fff6469fd5b -[_NSCollectionViewCore insertSections:] + 267
    4   UIFoundation                        0x00007fff6465dd5e -[_NSDiffableDataSourceViewUpdater _performNSCollectionViewInsertUpdate:] + 222
    5   UIFoundation                        0x00007fff6465db33 -[_NSDiffableDataSourceViewUpdater _performViewUpdates:] + 594
    6   AppKit                              0x00007fff3156d8e8 __58-[NSCollectionView performBatchUpdates:completionHandler:]_block_invoke + 21
    7   UIFoundation                        0x00007fff646aabe5 -[_NSCollectionViewCore _performBatchUpdates:completion:invalidationContext:tentativelyForReordering:animator:] + 323
    8   UIFoundation                        0x00007fff646aaa7f -[_NSCollectionViewCore _performBatchUpdates:completion:invalidationContext:tentativelyForReordering:] + 90
    9   UIFoundation                        0x00007fff646aaa02 -[_NSCollectionViewCore _performBatchUpdates:completion:invalidationContext:] + 74
    10  UIFoundation                        0x00007fff646aa957 -[_NSCollectionViewCore performBatchUpdates:completion:] + 53
    11  AppKit                              0x00007fff3156d7f4 -[NSCollectionView performBatchUpdates:completionHandler:] + 282
    12  UIFoundation                        0x00007fff6465d2ee -[_NSDiffableDataSourceViewUpdater _performUpdateWithCollectionViewUpdateItems:dataSourceSnapshotter:updateHandler:completion:] + 528
    13  UIFoundation                        0x00007fff646c72a2 -[__NSDiffableDataSource _commitNewDataSource:withViewUpdates:completion:] + 265
    14  UIFoundation                        0x00007fff646c1cb9 __66-[__NSDiffableDataSource applyDifferencesFromSnapshot:completion:]_block_invoke.259 + 190
    15  UIFoundation                        0x00007fff646c1fd2 __66-[__NSDiffableDataSource applyDifferencesFromSnapshot:completion:]_block_invoke.284 + 170
    16  libdispatch.dylib                   0x000000010039e78f _dispatch_client_callout + 8
    17  libdispatch.dylib                   0x00000001003af4cb _dispatch_lane_barrier_sync_invoke_and_complete + 135
    18  UIFoundation                        0x00007fff646c172d -[__NSDiffableDataSource applyDifferencesFromSnapshot:completion:] + 842
    19  UIFoundation                        0x00007fff64765417 +[_NSUIAnimator performWithAnimation:] + 90
    20  UIFoundation                        0x00007fff646c2939 -[__NSDiffableDataSource applyDifferencesFromSnapshot:animatingDifferences:completion:] + 158
    21  libswiftAppKit.dylib                0x00007fff6a2f6bb3 $s6AppKit34NSCollectionViewDiffableDataSourceC5apply_20animatingDifferences10completionyAA010NSDiffablefG8SnapshotVyxq_G_SbyycSgtF + 211
    22  DiffableTest                        0x0000000100005c73 $s12DiffableTest14ViewControllerC13performSearchyyyXlSgF + 3059

我是否以某种方式误用了API?
请参阅https://github.com/sbooth/DiffableTest以取得范例项目。

watbbzwu

watbbzwu1#

我发现 * 有时 * 有必要调用apply(_:animatingDifferences:)两次,一次是在调用appendSection(_:)和动画false之后,另一次是在调用appendItems(_:)之后。
例如:

extension AnimalsViewController {
    enum Section {
        case main
    }

    private func makeDataSource() -> UITableViewDiffableDataSource<Section, String> {
        UITableViewDiffableDataSource(tableView: tableView) { tableView, indexPath, name in
            let cell = tableView
                .dequeueReusableCell(withIdentifier: CellIdentifier.animalCell.rawValue,
                                     for: indexPath)

            cell.textLabel?.text = name
            return cell
        }
    }

    private func update() {
        activityIndicator.stopAnimating()
        var snapshot = NSDiffableDataSourceSnapshot<Section, String>()
        snapshot.appendSections([.main])
        dataSource.apply(snapshot, animatingDifferences: false)
        snapshot.appendItems(viewModel.animalNames)
        dataSource.apply(snapshot, animatingDifferences: true)
    }
}

oaxa6hgo

oaxa6hgo2#

在我进行了一些简短的测试之后,当数据源使用动画应用快照时,似乎会抛出section index out-of-bounds异常。如果在修改任何节时禁用动画,则不会抛出该异常。(至少在我的基本测试中不会。)
下面的代码 * 看起来 * 对我来说工作正常:

let outgoingSectionCount = dataSource.numberOfSections(in:collectionView)
let incomingSectionCount = snapshot.sectionIdentifiers.count

let shouldAnimate  = true
let canAnimate     = outgoingSectionCount == incomingSectionCount

dataSource.apply(snapshot, animatingDifferences:(shouldAnimate && canAnimate)

YMMV...

后续

正如您在上面的注解中所回避的,Apple DTS建议在您追加了节之后但在追加任何项之前调用dataSource.apply(...)。一旦成功插入了节,您就应该能够插入项并第二次调用dataSource.apply(...)

dauxcl2d

dauxcl2d3#

我自己也遇到了这个令人烦恼的问题。唯一可靠的修复方法是在应用快照之前使布局无效。

if snapshot.sectionIdentifiers.isEmpty {
    collectionView.collectionViewLayout.invalidateLayout()
}

dataSource.apply(snapshot, ...)
qlckcl4x

qlckcl4x4#

似乎一些与NSCollectionViewDiffableDataSource相关的错误已经在macOS 11中得到了解决。应用在macOS 10.15.* 中崩溃的带有动画的快照,似乎在macOS 11中的大多数情况下都可以工作。

相关问题