SwiftUI - nested list

╄→гoц情女王★ 提交于 2020-11-29 08:17:30

问题


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

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


回答1:


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

import SwiftUI

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)
        }
    }
}

struct TestNestedLists_Previews: PreviewProvider {
    static var previews: some View {
        TestNestedLists()
    }
}



回答2:


It's not hard, but you have to manually add some frame.

        struct SwiftUIViewList: View {
            var body: some View {
                    List {
                      Text("Hello, World!")
                      Text("Hello, World!")
                }
            }
        }

        struct SwiftUIView: View {
            var body: some View {

                List {

                   Text("item1")
                    SwiftUIViewList().frame(height: 100)
                   Text("item3")
                }
            }
        }


来源:https://stackoverflow.com/questions/58882673/swiftui-nested-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!