Assuming a sample model:
import Foundation
struct TreeNode: Hashable, Sendable {
let id = UUID()
let name: String
var children: [TreeNode]?
func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
static func == (lhs: TreeNode, rhs: TreeNode) -> Bool {
return lhs.id == rhs.id
}
}
enum TreeSection: CaseIterable {
case main
}
it can be accomplished with minimal effort since iOS 13.0
import UIKit
final class TreeListController: UIViewController {
typealias Item = TreeNode
typealias Section = TreeSection
typealias DS = UICollectionViewDiffableDataSource<Section, Item>
typealias DSSnapshot = NSDiffableDataSourceSnapshot<Section, Item>
typealias CellRegistration = UICollectionView.CellRegistration<UICollectionViewListCell, Item>
private let items: [Item]
private let collectionView: UICollectionView
private let dataSource: DS
init(treeNodes: [Item]) {
let collectionView = Self.createCollectionView()
let dataSource = Self.createDataSource(with: collectionView)
self.items = treeNodes
self.collectionView = collectionView
self.dataSource = dataSource
collectionView.dataSource = dataSource
super.init(nibName: nil, bundle: nil)
}
@available(iOS, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func loadView() {
view = collectionView
}
override func viewDidLoad() {
super.viewDidLoad()
applySnapshot(treeNodes: items, to: .main)
}
private static func createCollectionView() -> UICollectionView {
let config = UICollectionLayoutListConfiguration(appearance: .plain)
let layout = UICollectionViewCompositionalLayout.list(using: config)
return UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
}
private static func createDataSource(with collectionView: UICollectionView) -> DS {
let cellRegistration: CellRegistration = {
CellRegistration { cell, indexPath, treeNode in
var config = cell.defaultContentConfiguration()
config.image = UIImage(systemName: "folder")
config.imageProperties.tintColor = .systemBlue
config.text = treeNode.name
cell.contentConfiguration = config
// include disclosure indicator for nodes with children
cell.accessories = treeNode.children != nil ? [.outlineDisclosure()] : []
}
}()
return DS(collectionView: collectionView) { collectionView, indexPath, treeNode -> UICollectionViewCell? in
return collectionView.dequeueConfiguredReusableCell(using: cellRegistration, for: indexPath, item: treeNode)
}
}
private func applySnapshot(treeNodes: [TreeNode], to section: Section) {
// reset section
var snapshot = DSSnapshot()
snapshot.appendSections([section])
dataSource.apply(snapshot, animatingDifferences: false)
// initial snapshot with the root nodes
var sectionSnapshot = NSDiffableDataSourceSectionSnapshot<TreeNode>()
sectionSnapshot.append(treeNodes)
func addItemsRecursively(_ nodes: [TreeNode], to parent: TreeNode?) {
nodes.forEach { node in
// for each node we add its children, then recurse into the children nodes
if let children = node.children, !children.isEmpty {
sectionSnapshot.append(children, to: node)
addItemsRecursively(children, to: node)
}
// show every node expanded
sectionSnapshot.expand([node])
}
}
addItemsRecursively(treeNodes, to: nil)
dataSource.apply(sectionSnapshot, to: section, animatingDifferences: true)
}
}
Sample content:
let sampleTreeNodes = [TreeNode(name: "Folder 1", children: [
TreeNode(name: "Subfolder 1-1"),
TreeNode(name: "Subfolder 1-2", children: [
TreeNode(name: "File 1"),
TreeNode(name: "File 2")
])
])]
Bonus wrapper for SwiftUI:
import SwiftUI
import SwiftData
struct TreeListRepresentableView: UIViewControllerRepresentable {
typealias UIViewControllerType = TreeListController
let treeNodes: [TreeNode]
func makeUIViewController(context: Context) -> TreeListController {
TreeListController(treeNodes: createSampleFolderItems())
}
func updateUIViewController(_ uiViewController: TreeListController, context: Context) {
}
func createSampleFolderItems() -> [TreeNode] {
treeNodes
}
}
#Preview {
TreeListRepresentableView(treeNodes: sampleTreeNodes)
}
Tried it with ~50 folders, seems fine:
If you intend to show folder content, make the item AnyHashable, create Hashable models for each type of content, register each type of content, then cast the model with a switch when building the DS.