SwiftUI 全屏图像背景

问题描述 投票:0回答:3

我想在背景中显示全屏图像。我已经实现了这个:

struct LoginView: View {
    var body: some View {
        VStack {
            Spacer();
            Text("Hallo");
            Text("Hallo2");
            Text("Hallo2");
            Text("Hallo2");
            Text("Hallo2");
            Text("Hallo2");
            Text("Hallo2");
            Spacer();
            }.background(Image("Background LaunchScreen")
                .resizable()
                .aspectRatio(UIImage(named: "Background LaunchScreen")!.size, contentMode: .fill)
                .clipped())
            .edgesIgnoringSafeArea(.all)
    }
}

当我移除垫片时,图像不再以全屏模式显示。
当然可以用不同的方式解决吗?

如果我将模拟器中的 iPhone 转向一侧,我会看到左右白色条纹。
我该如何改变这个?

image background swiftui
3个回答
29
投票

这是使用

GeometryReader
ZStack
的可能解决方案:

import SwiftUI

struct LoginView: View {
    var body: some View {
        GeometryReader { geometry in
            ZStack {
                Image("LaunchImage")
                    .resizable()
                    .aspectRatio(geometry.size, contentMode: .fill)
                    .edgesIgnoringSafeArea(.all)
                VStack {
                    ForEach (1...10, id: \.self) { _ in
                        Text("Hallo")
                            .foregroundColor(Color.white)
                    }
                }
            }
        }
    }
}

#if DEBUG
struct LoginView_Previews: PreviewProvider {
    static var previews: some View {
        LoginView()
    }
}
#endif

结果


0
投票

为了让我的 VStack 正确,我必须这样做:ZStack(alignment: .leading)


0
投票

仅使用 ZStack:

import SwiftUI

struct ContentView: View {
    @State var allData = "hello "
    var body: some View {
        ZStack{
            Image("bg")
                .resizable()
                .aspectRatio(contentMode: .fill)
                .frame(minWidth: 0, maxWidth: .infinity)
                .edgesIgnoringSafeArea(.all)
            VStack {
                Image(systemName: "globe")
                    .imageScale(.large)
                    .foregroundStyle(.tint)
                Text("Hello, world!")
            }
            .padding()
        }
    }
}

#Preview {
    ContentView()
}

© www.soinside.com 2019 - 2024. All rights reserved.