Hi,
I have the following screen that has two lists in VStacks for each (combining a headline) that I put into another VStack which makes up the screen (see HomeExample).
I want the List (or better the VStack that contains a List) to size depending on the content of the List. So, for example, if the first List has just two elements, I want it to be smaller (at least if the second list hast more elements). If both lists have a lot elements, I want them to fair share the space.
Is there a way in SwiftUI to archive that?
import SwiftUI
struct MyList : View {
var headline: String
var items: [Item]
var body: some View {
VStack() {
Text(headline)
.font(.headline)
.padding(.top, 6)
List {
ForEach(items) { item in
ItemView(item: item)
}
}
}
}
}
struct ItemView: View {
var item: Item
var body: some View {
HStack {
Image(systemName: "square.stack.3d.up")
VStack(alignment: .leading) {
Text(item.headline)
.font(.headline)
Text(item.subHeadline)
.font(.subheadline)
}
}
}
}
struct Item: Identifiable {
var id: UUID
let headline: String
let subHeadline: String
}
struct HomeExample : View {
let items1: [Item]
let items2: [Item]
var body: some View {
VStack(alignment: .leading) {
MyList(headline: "The First List", items: items1)
MyList(headline: "The Second List", items: items2)
}
}
}
#if DEBUG
let testItems1 = [Item(id: UUID(), headline: "Blaa", subHeadline: "Sub Blaa"),
Item(id: UUID(), headline: "Bloo", subHeadline: "Sub Bloo"),
Item(id: UUID(), headline: "Blii", subHeadline: "Sub Blii"),
Item(id: UUID(), headline: "Blii", subHeadline: "Sub Blii"),
Item(id: UUID(), headline: "Blii", subHeadline: "Sub Blii"),
Item(id: UUID(), headline: "Blii", subHeadline: "Sub Blii"),
Item(id: UUID(), headline: "Blii", subHeadline: "Sub Blii"),
Item(id: UUID(), headline: "Blii", subHeadline: "Sub Blii"),
Item(id: UUID(), headline: "Blii", subHeadline: "Sub Blii"),
Item(id: UUID(), headline: "Blii", subHeadline: "Sub Blii")]
let testItems2 = [Item(id: UUID(), headline: "Foo", subHeadline: "Sub Foo"),
Item(id: UUID(), headline: "Fii", subHeadline: "Sub Fii"),
Item(id: UUID(), headline: "Faa", subHeadline: "Sub Faa")]
struct HomeExample_Previews : PreviewProvider {
static var previews: some View {
HomeExample(items1: testItems1, items2: testItems2)
}
}
#endif