使用 vstack 的全屏背景图像

full screen background image with vstack

我想要一个带导航视图的全屏背景图像(必须在顶部,因为它来自基础视图,而不是通常在 "this" 视图中)。 在此视图中,我想要一个位于安全区域内的 VStack,因此位于导航栏和底部布局之间。

不幸的是我得到了(见图)

我期待里面的文字...

struct ContentView: View {
    var body: some View {
        NavigationView {
            ZStack(alignment: .center) {

                Image("laguna")
                    .resizable()
                    .edgesIgnoringSafeArea(.all)
                    .scaledToFill()
                    .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)

                VStack(alignment: .center) {
                    Text("just a test")
                        .font(.largeTitle)
                        .foregroundColor(Color.white)
                    Spacer()
                    Text ("not centered....why?")
                        .font(.largeTitle)
                        .foregroundColor(Color.white)

                }
                .zIndex(4)
                .navigationBarTitle("nav bar title")
            }
        }
    }
}

这是一个稍微修改过的变体。使用 Xcode 11.4(最终发布)/iOS 13.4

进行测试

struct TestFullScreenImage: View {
    var body: some View {
        NavigationView {
            ZStack {
                Image("large_image")
                    .resizable()
                    .edgesIgnoringSafeArea(.all)
                    .scaledToFill()

                VStack {
                    Text("Just a test")
                        .font(.largeTitle)
                        .foregroundColor(.white)
                        Spacer()
                    Text("centered")
                        .font(.largeTitle)
                        .background(Color.green)
                }
                .navigationBarTitle("Navigation Title")
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}

如果需要使用NavigationView,并保持图片的纵横比,可以这样做:

import SwiftUI

struct FullScreenPictureDemo: View {
    var body: some View {
        NavigationView {
            ZStack {
                Image("your_full_screen_background_picture")
                    .resizable()
                    .aspectRatio(contentMode: .fill)
                    .edgesIgnoringSafeArea(.all)
                    .scaledToFill()
            }
        }
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
}