Creating UITableView with parent-child cells (Tree Structure)

Hi, I'm trying to implement a custom tableview which when tapped on a cell should expand and display its child cells, which further might have their children. Tapping again on the cell should collapse the view.

My data model looks something like below:

var objectTree = [
    MyObject(name: "Parent 1", id: "1", parentId: nil, children: [MyObject(name: "Child 1", id: "2", parentId: "1"), MyObject(name: "Child 2", id: "3", parentId: "1"),]),
    MyObject(name: "Parent 2", id: "4", parentId: nil, children: [MyObject(name: "Child 3", id: "5", parentId: "4", children: [MyObject(name: "Grandchild 1", id: "6", parentId: "5")])])
]

Here, "Parent 1" is the first cell, when tapped on it should expand and display its children "Child 1" & "Child 2" as sub/child cells under the "Parent 1" cell forming a tree-like structure.

Is there a way I can achieve this?

Hello @ganaraj-savant

Those forums are about Swift, the programming language, and not about Swift libraries such as UIKit or SwiftUI. In the future, please ask similar questions on the Apple developer forums, or stack overflow, and only use those forums for Swift-related questions only.

Now, I can't resist providing a quick answer: UITableView does not provide any parent-child feature, so you'll have to use elbow grease, code it yourself, or maybe look for a ready-made solution online. On the other hand, UICollectionView has built-in support for parent-child cells. Apple made an example app that you can download from Implementing Modern Collection Views. If you have further questions on this particular topic, remember to ask them in some other forums, thanks :-)

1 Like

and yet there are dedicated tags for frameworks like Kitura and Vapor, and a library like Alamofire :slight_smile:

Indeed one can find Kitura, Vapor, and Alamofire-related posts here, because those organisations have opted in for dedicated subforums ("categories") here. Other projects are hosted here: see the list of Related Projects.

UIKit and SwiftUI, on the other hand, do not have any dedicated category here.

And the "Using Swift" category (the category of this thread) is about Swift-the-language, not UIKit or SwiftUI.

Now, I didn't make the rules, and I'm not a cop, and I just wanted to help the OP get an accurate answer to the original question. Pure UIKit and SwiftUI questions have a better chance of finding an extended answer elsewhere, that's how things are :person_shrugging:

1 Like

I see :slight_smile: I'm still fairly new to this forum even though I have been a member for some time and I don't know all the rules and am just asking questions :slight_smile:

Thank you for explaining :slight_smile:

1 Like

Thank you for asking :)

1 Like