首页 > 解决方案 > SwiftUI 修复了从视图底部到屏幕顶部的约束

问题描述

问题:如何设置从视图底部到屏幕顶部的固定“约束”?

我的问题解释:我正在尝试在屏幕上实现这样的元素:

在此处输入图像描述

圆形,在所有屏幕上都有稳定的高度我用椭圆来画它

public var body: some View {
    VStack {
        ZStack(alignment: .bottom) {
            Ellipse()
                .fill(Color.surfacePrimary)
                .frame(width: 546, height: 364)
                .offset(x: 0, y: -20)
        
            Text("Text")
                .padding(.bottom, 60)
                .foregroundColor(.onPrimary)
        }
        .frame(minWidth: 0, idealWidth: .infinity, maxHeight: 20)
        .edgesIgnoringSafeArea(.top)

        Text("This text should be right below yellow shape, and it is, but on screens with not rectangle forms, on screens with rectangle form, it pops up on yellow zone")

        Spacer()
    }
}

问题:它在 iphone 11、12 上运行良好。但在 8、8+ 上,ZStack 的 SE(屏幕具有右矩形形式)框架移到顶部,但椭圆留在同一个地方。并且应该在黄色区域下方的视图移动到黄色区域。

UPD:我解决了 StatusBar 不同高度的问题,但现在我遇到了另一个以前无法观察到的问题。

我的新代码:

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 几乎填满了屏幕的所有高度。但我希望它应该有固定的高度。看起来像:

(嗯……上传图片有问题)

标签: swiftswiftui

解决方案


推荐阅读