首页 > 解决方案 > SwiftUI:防止视图在 VStack 内展开

问题描述

我有这样的 VStack,里面有列表

 VStack(alignment: .leading, spacing: 16) {
                        Text("Contacts")
                            .font(.custom("AvenirNext-DemiBold", size: 20))
                            .foregroundColor(Color("DarkTitle"))
                            .padding(8).layoutPriority(1)

                        List(self.contacts) { contact in
                            ContactOption(contact: contact)
                                .padding(.horizontal, 4)
                        } //.frame(height: 240)

  }

这段代码的问题是 List 试图尽可能多地扩展内容,尽管它只有 4 个联系人,但它占据了整个屏幕。

我可以使用将此高度设置为固定值frame(height: 240)

我认为是否有可能强制 List 像 Text() 视图一样包装其内容。即如果列表包装内容中有 4 行仅显示这 4 行,如果有 8 行扩展到这 8 行。然后我可以设置一些最大高度。400 上面的列表无法再展开,然后它将是可滚动的。

标签: listswiftuiswiftui-layout

解决方案


好的,我尝试了一下,我不确定你是否可以使用它,但请检查一下:(只需点击添加和删除即可查看列表如何变得越来越小)

struct ContactOption : View {

    var contact: String

    var body: some View {
        Text(contact)
    }
}

struct ListView : View {

    var contacts: [String]

    var body : some View {

        //        List(self.contacts, id: \.self) { contact in
        //            ContactOption(contact: contact)
        //                .padding(.horizontal, 4)
        //        }
        List {
            ForEach (contacts, id: \.self) { contact in
                Text (contact)
            }
        }
    }
}

struct ContentView: View {

    @State var contacts = ["Chris", "Joe", "Carla", "another"]

    var body: some View {
        VStack() {
            HStack {
                Button("Add") {
                    self.contacts.append("dust")
                }
                Button("Remove") {
                    self.contacts = self.contacts.dropLast()
                }
            }
            Text("Contacts")
                .foregroundColor(Color.blue)
                .padding(8).layoutPriority(1)

            Form {
                ListView(contacts: contacts)
                Section(footer: Text("hi")) {
                    Text("hi")
                }
            }

            Divider()
            Text("end list")
                .foregroundColor(Color.orange)

        }
    }
}

推荐阅读