You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否自定义UICollectionView列表样式outlineDisclosure的布局及实现自定义展开控制?

实现方案

可以通过代码控制对应分区的展开和收起,核心是操作NSDiffableDataSourceSectionSnapshot的expand(_:)和collapse(_:)方法切换状态,再应用到数据源即可。

具体修改步骤

直接修改你的headerCellRegistration逻辑即可:

let headerCellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, HeaderItem> {
    [weak self] (cell, indexPath, headerItem) in
    var config = cell.defaultContentConfiguration()
    config.text = headerItem.title
    cell.contentConfiguration = config
    
    guard let self = self else { return }
    // 获取当前分区的快照,读取展开状态
    let currentSectionSnapshot = self.dataSource.snapshot(for: headerItem)
    let headerListItem = ListItem.header(headerItem)
    let isExpanded = currentSectionSnapshot.isExpanded(headerListItem)
    
    // 生成切换展开状态的按钮
    let toggleButton = UIButton(primaryAction: UIAction(
        image: UIImage(systemName: isExpanded ? "chevron.down" : "chevron.up")
    ) { _ in
        var updatedSnapshot = currentSectionSnapshot
        // 切换展开/收起状态
        isExpanded ? updatedSnapshot.collapse([headerListItem]) : updatedSnapshot.expand([headerListItem])
        // 应用更新后的快照,自动触发动画
        self.dataSource.apply(updatedSnapshot, to: headerItem, animatingDifferences: true)
    })
    
    // 配置左侧自定义指示器
    let customAccessoryConfig = UICellAccessory.CustomViewConfiguration(
        customView: toggleButton,
        placement: .leading(displayed: .always)
    )
    cell.accessories = [.customView(configuration: customAccessoryConfig)]
}

注意事项

  • 原有代码中的outlineDisclosure相关配置需要移除,避免和自定义指示器冲突
  • 每次状态更新后,cell会重新执行注册闭包逻辑,自动刷新指示器的图标,不需要手动管理按钮状态

内容的提问来源于stack exchange,提问作者finebel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 17:36:03