[英]SwiftUI HStack fill whole width with equal spacing
我有一个 HStack:
struct BottomList: View {
var body: some View {
HStack() {
ForEach(navData) { item in
NavItem(image: item.icon, title: item.title)
}
}
}
}
如何以等间距自动填充整个宽度,使其内容完美居中?
仅供参考,就像引导程序 CSS class .justify-content-around
frame
布局修改器, maxWidth
参数为.infinity
可用于实现此目的,而无需额外的Shape
View。
struct ContentView: View {
var data = ["View", "V", "View Long"]
var body: some View {
VStack {
// This will be as small as possible to fit the data
HStack {
ForEach(data, id: \.self) { item in
Text(item)
.border(Color.red)
}
}
// The frame modifier allows the view to expand horizontally
HStack {
ForEach(data, id: \.self) { item in
Text(item)
.frame(maxWidth: .infinity)
.border(Color.red)
}
}
}
}
}
各种*Stack
类型将尝试缩小到可能包含其子视图的最小尺寸。 如果子视图有一个理想的大小,那么*Stack
将不会扩展以填满屏幕。 这可以通过将每个子项放在ZStack
中一个清晰的Rectangle
顶部来克服,因为Shape
会尽可能地扩展。 一种方便的方法是通过View
上的扩展:
extension View {
func inExpandingRectangle() -> some View {
ZStack {
Rectangle()
.fill(Color.clear)
self
}
}
}
然后你可以这样称呼它:
struct ContentView: View {
var data = ["View", "View", "View"]
var body: some View {
VStack {
// This will be as small as possible to fit the items
HStack {
ForEach(data, id: \.self) { item in
Text(item)
.border(Color.red)
}
}
// Each item's invisible Rectangle forces it to expand
// The .fixedSize modifier prevents expansion in the vertical direction
HStack {
ForEach(data, id: \.self) { item in
Text(item)
.inExpandingRectangle()
.fixedSize(horizontal: false, vertical: true)
.border(Color.red)
}
}
}
}
}
您可以根据需要调整HStack
上的间距。
我在每个项目之后插入了Spacer()
......但对于最后一个项目,不要添加Spacer()
:
struct BottomList: View {
var body: some View {
HStack() {
ForEach(data) { item in
Item(title: item.title)
if item != data.last { // match everything but the last
Spacer()
}
}
}
}
}
(注意:接受的答案.frame(maxWidth: .infinity)
不适用于所有情况:当涉及到具有不同宽度的项目时,它对我不起作用)
如果您的数组有重复值,请使用 array.indices 在最后一个元素之后省略一个分隔符。
HStack() {
ForEach(data.indices) { i in
Text("\(data[i])")
if i != data.last {
Spacer()
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.