Created
January 21, 2021 15:06
-
-
Save mgcm/254a9952a55d43de3f576aa4a2c17efc to your computer and use it in GitHub Desktop.
Recursive Menu Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
struct MenuItem { | |
var title = "" | |
var children: [MenuItem]? | |
} | |
struct Menu { | |
var title = "" | |
var items: [MenuItem] = [] | |
} | |
var items = [ | |
MenuItem( | |
title: "Item 1", | |
children: [ | |
MenuItem(title: "Item 1-1", children: []), | |
MenuItem(title: "Item 1-2", children: [ | |
MenuItem(title: "Item 1-2-1", children: []), | |
]), | |
]), | |
MenuItem( | |
title: "Item 2", | |
children: []), | |
MenuItem( | |
title: "Item 3", | |
children: [ | |
MenuItem(title: "Item 3-1", children: [ | |
MenuItem( | |
title: "Item 3-1-1", | |
children: [ | |
MenuItem(title: "Item 3-1-1-1", children: []) | |
]), | |
]), | |
]) | |
] | |
var menu = Menu(title: "/", items: items) | |
import UIKit | |
import PlaygroundSupport | |
import Foundation | |
class TableViewController: UITableViewController { | |
var menuItems: [String] = [] | |
var level = 0 | |
/*** IMPORTANT STUFF ***/ | |
func buildMenu(_ menu: Menu) { | |
menuItems.append(menu.title) | |
getChildren(menu.items) | |
} | |
func getChildren(_ items: [MenuItem]) { | |
for item in items { | |
level += 1 | |
let prefix = String(repeating: "\t", count: level) | |
menuItems.append(prefix + " -> " + item.title) | |
if let children = item.children { | |
getChildren(children) | |
} | |
} | |
level -= 1 | |
return | |
} | |
/*** END OF IMPORTANT STUFF ***/ | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
buildMenu(menu) | |
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") | |
} | |
override func numberOfSections(in tableView: UITableView) -> Int { | |
return 1 | |
} | |
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { | |
return menuItems.count | |
} | |
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { | |
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell | |
cell.textLabel?.text = menuItems[indexPath.row] | |
return cell | |
} | |
} | |
let controller = TableViewController() | |
PlaygroundPage.current.liveView = controller |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment