我有这样的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)
}
此代码的问题在于,尽管只有4个联系人,但List试图在此范围内尽其所能扩展整个屏幕。
我可以使用frame(height: 240)
将此高度设置为固定值
我认为,是否有可能像Text()视图一样强制执行List来包装其内容。 也就是说,如果列表包装内容中有4行仅显示这4行,则如果有8行则扩展到这8行。然后我可以设置一些最大高度ex。 400以上,列表无法再扩展,然后它将可以滚动。
答案 0 :(得分:0)
好吧,我尝试了一下,但不确定是否可以使用它,但请检查一下:(只需点击添加和删除以查看列表越来越大)
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)
}
}
}