SwiftUI: Prevent view being inside VStack to expand

2.1k Views Asked by At

I have such VStack with list inside it

 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)

  }

The problem with this code is that List tries to expand content as much as it can here taking up entire screen in spite of having just 4 contacts.

I can set this height to fixed value using frame(height: 240)

I consider wether there is possibility to enforce List to wrap its content like Text() view does. i.e. if there is 4 rows in List wrap content to display just this 4 rows, if there is 8 rows expand to this 8 rows. Then I could set some max height ex. 400 above which List could not expand anymore and then it will be scrollable.

1

There are 1 best solutions below

1
On

ok, i tried a bit and i am not sure whether you can use it or not, but check this out: (just tap on add and remofe to see how the list gets bigger and smaller)

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)

        }
    }
}