SwiftUI:如何在父视图中心叠加图像?

4

我有一张图片,它与现有视图顶部对齐,但我想让它居中显示在屏幕上(或者是三文鱼色区域内)。

应该在三文鱼色区域居中显示

以下是我的代码:

struct LeaderBoard: View {
    @State var shouldDisplayOverLay = true
    var body: some View {
        ZStack {
            VStack(alignment: .center) {
                Text("Daily Dashboard")
                    .font(.subheadline)
                Color.darkSalmon
                Spacer()
                HStack {
                    Text("Exercise")
                    Text("Sleep (in hours):")
                    Text("Weight") // red if lower more than a pound, yellow if less than pound, green if same or higher
                }
                .font(.caption)
                Spacer()
            }
            Image("Leader-1024")
                .resizable()
                .scaledToFit()
                .modifier(InsetViewModifier())
        }
    }
}


struct InsetViewModifier: ViewModifier {
    func body(content: Content) -> some View {
        GeometryReader { proxy in
            content
                .frame(width: proxy.size.width * 0.8, height: proxy.size.height * 0.8, alignment: .center)
        }
    }
}
1个回答

3

GeometyReader 没有自己的对齐方式,因此解决方案可以是在修饰符中嵌入一些堆栈(因为它们所有的默认都具有 .center 对齐):

struct InsetViewModifier: ViewModifier {
    func body(content: Content) -> some View {
        GeometryReader { proxy in
            VStack {
                content
                    .frame(width: proxy.size.width * 0.8, height: proxy.size.height * 0.8, alignment: .center)
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity)
        }
    }
}

以及一些复制的演示

演示


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接