英文:
SwiftUI ForEach block takes more space if there is only one item
问题
当我使用这段代码时,我希望在向 ForEach 视图添加新项时,ScrollView 和 ForEach 视图能够扩展。但目前它只会填充一些大于 ForEach 区块内视图的空间。我该如何使它仅填充 ForEach 代码块内视图大小的空间?
ScrollView {
ForEach(files, id: \.self) { item in
HStack {
Image("file")
Text(item)
.lineLimit(1)
Spacer()
Button {
files.removeAll(where: { $0 == item })
} label: {
Image("close")
}
}
}
}
我尝试过为 ScrollView 设置 minWidth 和 maxWidth,但似乎没有起作用。
英文:
When I use this block of code, I want ScrollView and ForEach views to expand when new items are added to ForEach view. But currently it just fills some space that is larger than the view inside ForEach block. How can I make it fill space for only views sizes inside ForEach block of code?
ScrollView {
ForEach(files, id: \.self) { item in
HStack {
Image("file")
Text(item)
.lineLimit(1)
Spacer()
Button {
files.removeAll(where: { $0 == item })
} label: {
Image("close")
}
}
}
}
I tried setting minWidth and maxWidth for scroll view. But that doesn't seem to work
答案1
得分: 1
I don't really get what's your issue with the scrollView filling all the available empty space but if you really need to fix the ScrollView height to the minimum you can add .fixedSize(horizontal: false, vertical: true)
to your ScrollView content closure.
.fixedSize
will tell the view to resize to its optimal frame (most of the time the smallest possible), but the view expanding in SwiftUI is the default way (cause view will automatically resize looking at their neighbors) and I see no point in preventing the ScrollView from expanding, can you give more details about what you are trying to achieve?
Result (before/after fixedSize) using your code with the scroll view in red
and the foreach in blue
英文:
I don't really get what's your issue with the scrollView filling all the available empty space but if you really need to fix the ScrollView height to the minimum you can add .fixedSize(horizontal: false, vertical: true)
to your ScrollView content closure.
.fixedSize
will tell the view to resize to its optimal frame (most of the time the smallest possible), but the view expanding in SwiftUI is the default way (cause view will automatically resize looking at their neighbors) and I see no point in preventing the ScrollView from expanding, can you give more details about what you are trying to achieve?
Result (before/after fixedSize) using your code with the scroll view in red
and the foreach in blue
答案2
得分: 0
id: \.self
需要更改为 id: \.someUniqueProperty
。
英文:
id: \.self
needs to be changed to id: \.someUniqueProperty
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论