5

I'm looking at creating some sort of visual representation of a tree data structure in iOS. The data held by a node in the tree is an image and a label, and a node can have up to 6 children.

Currently, I have a collection view with a custom layout where I programmatically calculate the x and y of each node as I traverse my homemade tree.

This solution works, but just barely. As I build more functionality, I expect it to fall apart.

I've considered making an image once the tree is constructed and just using an imageview, but I plan on implementing some sort of expand/collapse on branches. I also need a way to zoom in and out on the whole tree, which doesn't seem very easy with collection views.

Is there a better solution out there?

3 Answers 3

4
+25

What about using just simple views inside a UIScrollView?

This way you could:

  • Control expanding and collapsing each node.
  • Zoom in and out for an overall or detail view.
  • Scrolling in case of huge tree structures.

Here I created an example project using UIViews: https://github.com/crisisGriega/swift-simple-tree-drawer

It was a quick development so there are a lot of things that can be improved, like the way the lines (connectors) between the nodes are drawn. Also in this example the nodes are added to a UIView instead of a UIScrollView. But you can tap on the nodes to show/hide its children.

1

Consider using SpriteKit rather than using UIKit components. It's not easy to create dynamic tree-like layout using UICollectionView as you can look at its data source definition, it's not meant to model tree data, but flat list data. If the data model is fundamentally different, everything becomes difficult to procceed.

With SpriteKit, your node objects can each be renderred by a SKSpriteNode object. Layouting child nodes is managed by their parent node. You can use the physics engine to automatically position nodes as well, and it comes with the additional benefit that overlapping can be avoided with minimum efferot. Last but not least, scaling and scrolling are supported out of the box by SpriteKit.

0

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:

folder tree

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.