我有一个快速视图,该视图由带有矩形的HStack和内部的Vstack文本组成。我想使矩形的高度与Vstack的高度相同。我已经尝试过在StackOverflow上浏览许多其他问题,但没有找到答案。有人可以帮我吗?
这是我的代码:
struct TodoView: View {
@State var todos = ["feed the dog", "take the dog out for a walk", "make coffee"]
@State var height: CGFloat = 45
var body: some View {
HStack{
RoundedRectangle(cornerRadius: 2)
.frame(width: 1)
.foregroundColor(Color("lightGray"))
.padding()
VStack{
Text("Todo")
.font(.title)
ForEach(todos, id: \.self){ todo in
Text(todo)
}
}
Spacer()
}
}
}
答案 0 :(得分:2)
您需要了解GeometryReader和PreferenceKey才能实现这一点。
struct SiblingHeightKey: PreferenceKey {
static var defaultValue: CGSize? {
nil
}
static func reduce(value: inout CGSize?, nextValue: () -> CGSize?) {
value = value ?? nextValue()
}
}
struct TodoView: View {
@State var vStackSize: CGSize? = nil
@State var todos = ["feed the dog", "take the dog out for a walk", "make coffee"]
@State var height: CGFloat = 45
var body: some View {
HStack{
RoundedRectangle(cornerRadius: 2)
.foregroundColor(.gray)
.frame(width: self.vStackSize?.width, height: self.vStackSize?.height)
VStack{
Text("Todo")
.font(.title)
ForEach(todos, id: \.self){ todo in
Text(todo)
}
}.background(
GeometryReader { proxy in
Color.clear.preference(key: SiblingHeightKey.self, value: proxy.size)
}
)
Spacer()
}.onPreferenceChange(SiblingHeightKey.self) {
self.vStackSize = $0
}
}
}
答案 1 :(得分:0)
您可以使用.frame
修饰符:
HStack{
RoundedRectangle(cornerRadius: 2)
.frame(width: 1, height: 50)
.foregroundColor(Color("lightGray"))
.padding()
VStack {
Text("Todo")
.font(.title)
ForEach(todos, id: \.self){ todo in
Text(todo)
}
.frame(height: 50)
}
Spacer()
}
如果要让它们填充整个View
:
.frame(minWidth: 0, maxWidth: .infinity)
或者,您可以使用此处建议的GeometryReader
:Make a grid of buttons of same width and height in SwiftUI。