首页 > 解决方案 > SwiftUI ZStack 采用所有屏幕高度,但应该是固定高度

问题描述

我的代码:

public var body: some View {
    ZStack(alignment: .bottom) {
        Ellipse()
            .fill(.yellow)
        Text("Text")
            .padding(.bottom, 42)
            .foregroundColor(.red)
    }
    .frame(width: 546, height: 364)
    .position(x: UIScreen.main.bounds.size.width / 2, y: Spacing.padding_0_5)
    .edgesIgnoringSafeArea(.top)
    .background(Color.red)
}

使得 ZStack 几乎占据了所有屏幕高度。但我希望它会从 .frame() 方法中获取高度。

标签: iosswiftswiftui

解决方案


我有一个解决方法给你,它有点乱但有效

 public var body: some View {
        ZStack {
            ZStack(alignment: .bottom) {
                Ellipse()
                    .fill(.yellow)
                
            }
            .frame(width: 546, height: 364)
            .position(x: UIScreen.main.bounds.size.width / 2, y: Spacing.padding_0_5)
            .edgesIgnoringSafeArea(.top)
            .zIndex(0)
            ZStack {
                VStack {
                    VStack {
                        Text("Text")
                            .padding(.top, 42)
                            .foregroundColor(.red)
                    }
                    .frame(width: UIScreen.main.bounds.width, height: 182)
                    VStack {
                        Text("Your texts here")
                    }
                    .frame(width: UIScreen.main.bounds.width)
                    Spacer()
                }
                .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
            }
            .zIndex(1)
        }
        .background(Color.red)
    }

我只是在另一层上制作了你的椭圆,在另一层上制作了文字。

ZStack(alignment: .bottom) {
   Ellipse()
       .fill(.yellow)
   }
   .frame(width: 546, height: 364)
   .position(x: UIScreen.main.bounds.size.width / 2, y: Spacing.padding_0_5)
   .edgesIgnoringSafeArea(.top)
   .zIndex(0)

.zIndex(0)确保视图在后台。

ZStack {
    VStack { // This VStack contains all your text
        VStack { // First VStack
            Text("Text")
                .padding(.top, 42)
                .foregroundColor(.red)
        }
       .frame(width: UIScreen.main.bounds.width, height: 182)
        VStack { //Second VStack
             Text("Your texts here")
        }
        .frame(width: UIScreen.main.bounds.width)
         Spacer()
    }
    .frame(width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height)
}
.zIndex(1)

在这里,ZStack占据了整个屏幕。我们添加了一个VStack包含您的文本的内容。

  • 第一个VStack在椭圆上有主标签,它的框架是根据椭圆的高度硬编码的(椭圆的另一半在屏幕外的高度的 1/2)。
  • 第二个VStack从我们第一个的末尾开始,VStack这是所需的功能,最后添加了一个spacer(),以便将文本放置在顶部而不是中间。

zIndex(1)确保放置在元素上zIndex(0)


推荐阅读