我有一个前景视图和一个背景视图。前景视图包含一些文本,图像和几个堆栈视图。它会自动调整大小并看起来很完美。我想添加一个与我的前景视图的自动尺寸匹配的背景视图。我的背景视图是由一些形状组成的View
。
我尝试过的事情:
ZStack
,我的背景视图会自动调整大小(填充容器)。struct ForegroundView: View {
var body: some View {
HStack {
Image(systemName: "photo")
VStack(alignment: .leading) {
Text("Title")
Text("Subtitle")
}
Spacer()
Text("42")
}
}
}
struct ForegroundView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
背景视图是进度条。
struct ProgressBar: View {
@Binding var value: Float
var body: some View {
GeometryReader { gr in
ZStack(alignment: .leading) {
Rectangle()
.frame(width: gr.size.width,
height: gr.size.height)
.opacity(0.3)
.foregroundColor(Color(UIColor.systemTeal))
Rectangle()
.frame(width: min(CGFloat(self.value)*gr.size.width, gr.size.width),
height: gr.size.height)
.foregroundColor(Color(UIColor.systemBlue))
.animation(.linear)
}
}
}
}
struct ProgressBar_Previews: PreviewProvider {
static var previews: some View {
ProgressBar(value: .constant(0.5))
}
}
struct Demo_Preview: PreviewProvider {
static var previews: some View {
Group {
// Attempt 1
ZStack {
ProgressBar(value: .constant(0.5))
ForegroundView()
}
// Attempt 2
ForegroundView().overlay(ProgressBar(value: .constant(0.5)))
// Attempt 3
ProgressBar(value: .constant(0.5)).overlay(ForegroundView())
}
}
}
答案 0 :(得分:0)
事实证明,答案很简单:background modifier。
struct Demo_Preview: PreviewProvider {
static var previews: some View {
Group {
ForegroundView().background(ProgressBar(value: .constant(0.5)))
}
}
}