SwiftUI: OutlineGroup
To implement the above screen using UIKit, we used to play with UITableView and massive coding (number of delegate and data source functions) and also, need to maintain boolean for expand and collapse functionality.
In this blog, I am going to implement the above view with SwiftUI:
Requirement: Xcode 12 beta
Apple introduces a new type of View in SwiftUI: OutlineGroup. By this feature, the view can represent a hierarchy of data by using disclosure views with just a few lines of code. This allows the user to view the tree structure by using disclosure views to expand and collapse branches
In the below example, I am trying to turn the List into Outline view. I just need to give proper data(tree-like structure) and rest will be handle by the OutlineGroup by traversing through the data. Data may contain groups, and groups can also contain subgroups. so to display this kind of data, we need to represent an arbitrarily deep tree of elements.
Below is the code snapshot of OutlineGroup with List:(Code snippet can be find on https://www.iostutorials.co.in/2020/07/switui-outlinegroup.html)
I use a ForEach to iterate over canvases. For each canvas, we use Section to add a header showing the name of the canvas. And finally, the content of the section is a view, new to SwiftUI: an OutlineGroup. An OutlineGroup is similar to a ForEach except that instead of iterating over a flat collection, OutlineGroup traverses tree structure data. Here it traverses through an array of fruits or vegetables and their children’s elements.
SwiftUI Outline group not only works with macOS, but it also works with iOS and iPad OS
By writing a few lines of code and with a proper Data model, I can tap the disclosure indicator to expand and collapse to see the list of fruits and types of apples which is the subcategory of fruits.
Conclusion: You can traverse through the tree-like data model with OutlineGroup. In this blog using the outline Group, I have represented the arbitrarily deep tree of elements. However, We can use OutlineGroup without List view to display the Outline structure but the structure of UI might differ.
For the reference, I have uploaded whole code on below path
https://github.com/pankajtalreja2503/OutlineGroupSwiftUI.git
You can check out my other blogs by just one click: https://www.iostutorials.co.in/
Stay tuned for more updates on SwiftUI :)