list - 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 上面的列表无法再展开,然后它将是可滚动的。
解决方案
好的,我尝试了一下,我不确定你是否可以使用它,但请检查一下:(只需点击添加和删除即可查看列表如何变得越来越小)
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)
}
}
}
推荐阅读
- sql - 如何在 Oracle SQL 中查找最近 7 个工作日/工作日?
- froala - 使用 CTRL + V FROALA 粘贴图像时出错
- javascript - 这如何转换为 JSS?
- css - 背景图像上的内联线性渐变
- sql - BigQuery/SQL:根据右起第二个点拆分字符串
- html - 使用css动画条件*ngIf div高度
- alignment - Wix:将图像停靠在屏幕右侧(不是网格)
- python - 如何将跳过的行的内容添加到数据框中的前一行
- javascript - 我如何使这个购物篮工作,并且只有在添加了某些东西时才让它显示出来。使用 vue.js?
- javascript - WebRTC 发送立体声音频流,接收单声道音频流