Introduction
I love the TreeView
in .NET and am wanting one for an iPad app, but discovered that iOS does not have a TreeView
control so after hunting around, I just decided to write one of my own.
Background
I did find a few iOS Tree Views on various sites, but they were all old and used Objective-C with no clear instructions on adding to your project, so that was just not going to work out.
However, I did find a fairly easy one by Ahmed Karim written in Objective-C that I downloaded and looked at and used some of his ideas.
Ahmed Karim's project => This is A Tree Control That Works on iOS Devices
Using the Code
I started with the Single View Application in XCode. I added a tableView
to the main View Controller and then set the attributes to use TreeViewController
.
I also created a custom cell and set that to use TreeViewCell
.
The Data for the Tree is loaded in TreeLists.swift
. It is an array of a class called TreeViewData
. Be sure to use a unique id for each one and then for the children nodes, set the parentId
to the id of the node they belong under. Set the Zero level parentId
to something that is not going to be used.
static func LoadInitialData() -> [TreeViewData]
{
var data: [TreeViewData] = []
data.append(TreeViewData(level: 0, name: "cindy's family tree", id: "1", parentId: "-1")!)
data.append(TreeViewData(level: 0, name: "jack's family tree", id: "2", parentId: "-1")!)
data.append(TreeViewData(level: 1, name: "katherine", id: "3", parentId: "1")!)
data.append(TreeViewData(level: 1, name: "kyle", id: "4", parentId: "1")!)
data.append(TreeViewData(level: 2, name: "hayley", id: "5", parentId: "3")!)
data.append(TreeViewData(level: 2, name: "macey", id: "6", parentId: "3")!)
data.append(TreeViewData(level: 1, name: "katelyn", id: "7", parentId: "2")!)
data.append(TreeViewData(level: 1, name: "jared", id: "8", parentId: "2")!)
data.append(TreeViewData(level: 1, name: "denyee", id: "9", parentId: "2")!)
data.append(TreeViewData(level: 2, name: "cayleb", id: "10", parentId: "4")!)
data.append(TreeViewData(level: 2, name: "carter", id: "11", parentId: "4")!)
data.append(TreeViewData(level: 2, name: "braylon", id: "12", parentId: "4")!)
data.append(TreeViewData(level: 3, name: "samson", id: "13", parentId: "5")!)
data.append(TreeViewData(level: 3, name: "samson", id: "14", parentId: "6")!)
return data
}