SwiftUI 如何使用图像和其他视图作为背景?

5 min read

要在 SwiftUI 中使用图像和其他视图作为背景,可以使用 background 修饰符来设置视图的背景。以下是一些示例代码:

  1. 将图像作为背景
struct ContentView: View {
    var body: some View {
        Image("background-image")
            .resizable()
            .scaledToFill()
            .edgesIgnoringSafeArea(.all)
            .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
    }
}
  1. 将颜色作为背景
struct ContentView: View {
    var body: some View {
        Color.red
            .edgesIgnoringSafeArea(.all)
    }
}
  1. 将其他视图作为背景
struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello, World!")
            Spacer()
        }
        .padding(.all)
        .background(Color.blue)
    }
}

在这个例子中,我们将一个垂直的 VStack 视图作为主视图,然后使用 background 修饰符将它的背景设置为蓝色。