使用 SwiftUI 在背景图像上方放置顶部栏

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

我希望背景图像和绿色 UI 元素位于屏幕顶部,但代码位于绿色 UI 元素下方的中间。

代码:

struct AppointmentStep1: View {

    @Environment(\.dismiss) var dismiss

    var body: some View {
        ZStack {
            // Background image
            Image("home_bg")
                .resizable()
                .scaledToFill()
                .edgesIgnoringSafeArea(.all)
            VStack {
                HStack {
                    Button  {
                        dismiss()
                    } label: {
                        Image(systemName: "arrow.left")
                            .font(.system(size: 25))
                            .tint(.white)
                            .padding(.trailing, 6)
                    }

                    Text("Appointment")
                        .font(.calibriRegular(with: 20))
                        .foregroundStyle(.white)
                    Spacer()
                }
                .padding(16)
            }
            .background(
                Color.appGreen2
                    .ignoresSafeArea()
            )

           Spacer()
        }
    }
}

o/p:如何将绿色视图移动到顶部

enter image description here

编辑:

enter image description here

swift swiftui
2个回答
0
投票

您可以简单地为ZStack设置

alignment
,默认为
.center

ZStack(alignment: .top) { 
    ...
}

0
投票

为了达到我认为您期望的结果,首先您需要将

Spacer
ZStack
移动到
VStack
。以下是编辑后的代码片段供您参考:

var body: some View {
  ZStack {
    Image("home_bg")
      .resizable()
      .scaledToFill()
      .edgesIgnoringSafeArea(.all)
    VStack {
      HStack {
        Button { dismiss() } label: {
          Image(systemName: "arrow.left")
            .font(.system(size: 25.0))
            .tint(.white)
            .padding(.trailing, 6.0)
          }
          Text("Appointment")
            .font(.calibriRegular(with: 20))
            .foregroundStyle(.white)
          Spacer()
        }
          .padding(.vertical, 16.0)
          .padding(.horizontal, 32.0)
          .background(
            Color
              .appGreen2
              .ignoresSafeArea()
          )
      Spacer()
    }
  }
}

结果如下:

enter image description here

(在屏幕截图上,您会看到另一个背景图像和另一个绿色,因为我显然没有您的非标准资产。)

我还使用了

Button
的填充来修复它们——也许这是你想要修复的另一件事。

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