Tuesday, July 19, 2016

Collection View Tree Representation

Leave a Comment

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

Answers 1

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.

Answers 2

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.

Answers 3

I think, it is good that you design your own view programmatically. It seems difficult but it is the easiest method. Designing your own view is really simple and just use your imagination you can create what you want.

If You Enjoyed This, Take 5 Seconds To Share It

0 comments:

Post a Comment