Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SwiftUI - nested list

I'm trying to create a nested hierarchical list, so that for each task I can have subtasks like in iOS reminders app:

enter image description here

First attempt was to embed another list inside a list cell.

import SwiftUI

struct SwiftUIView: View {
    var body: some View {

        List {
            List {
              Text("Hello, World!")

            }

        }
    }
}

struct SwiftUIView_Previews: PreviewProvider {
    static var previews: some View {
        SwiftUIView()
    }

But, didn't work out...

Anyone can help?

cheers

like image 853
Mane Manero Avatar asked Nov 15 '19 18:11

Mane Manero


People also ask

How do I create a custom list in SwiftUI?

To begin, create a SwiftUI Xcode project, and create a struct , namely, Data . Let's get back in our ContentView. swift and populate some values into this struct . Now, inside your view, create a List, and use ForEach to add and see all your data in list form.

How do I show a list in SwiftUI?

Enter SwiftUIListTutorial as the Product Name, select the Use SwiftUI checkbox, and click Next. Choose a location to save the project on your Mac. In the canvas, click Resume to display the preview. If the canvas isn't visible, select Editor > Editor and Canvas to show it.


1 Answers

Why do you think it should be List in List... Such visual representation can be generated using only one list and it will have native look & feel.

Here is just a demo (w/o UI tuning and logic of showing/hiding sections, that is out of topic), but the idea should be clear

nested list

struct ItemRow: View {
    let category: Bool
    let text: String
    
    init(_ text: String, isCategory: Bool = false) {
        self.category = isCategory
        self.text = text
    }
    
    var body: some View {
        HStack {
            Circle().stroke() // this can be custom control
                .frame(width: 20, height: 20)
                .onTapGesture {
                    // handle tap here
                }
            if category {
                Text(self.text).bold()
            } else {
                Text(self.text)
            }
        }
    }
}

struct TestNestedLists: View {
    var body: some View {
        List { // next pattern easily wrapped with ForEach
            ItemRow("Category", isCategory: true) // this can be section's header
            Section {
                ItemRow("Item 1")
                ItemRow("Item 2")
                ItemRow("Item 3")
            }.padding(.leading, 20)
        }
    }
}

backup

like image 100
Asperi Avatar answered Sep 19 '22 16:09

Asperi