首页 > 解决方案 > 如何将其移至顶部?

问题描述

我刚刚学会了如何实现特定的圆角,但现在似乎没有任何东西可以与屏幕顶部对齐,即使有垫片也是如此。如何让它与屏幕顶部对齐?

此外,我希望果岭忽略顶部安全区域,但它之前也没有这样做。

import SwiftUI

struct Dashboard: View {
    
    @State var bottomLeft: CGFloat = 25
    
    var body: some View {
        ZStack {
            Color("background")
                .edgesIgnoringSafeArea(.all)
            
            VStack {
                VStack {
                    Text("Good Morning, Sarah")
                        .font(Font.system(size: 36))
                        .foregroundColor(.standaloneLabelColor)
                        .fontWeight(.semibold)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding(.horizontal)
                    
                    Text("We're glad to see you and hope you're doing well. Let's take on the day.")
                        .font(Font.system(size: 20))
                        .foregroundColor(.standaloneLabelColor)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .padding(.horizontal)
                        .padding(.bottom)
                }
                .background(Color.appColor)
                .cornerRadius(bottomLeft, corners: .bottomLeft)
                .padding(.bottom, 10)
            
            
        }
            
            Spacer()
        }
        
    }
}

提前致谢。

标签: swiftswiftuialignmentsafearea

解决方案


ZStack您可以在to上设置对齐方式.top。然后,您还可以删除Spacer.

ASpacer在 a - 中什么也不做ZStack,因为它在自己的层上。但是设置对齐方式ZStack会将所有视图对齐到顶部。如果这不是你想要的,你也可以把它Spacer放在内部VStack,它的内容也将全部与顶部对齐。

代码:

ZStack(alignment: .top) {
    Color("background")
        .edgesIgnoringSafeArea(.all)

    VStack {
        /* ... */
    }
}

此外,要在应用圆角时忽略顶部的安全区域,您应该剪掉角并使用ignoresSafeArea()within background。这确保您只忽略背景的安全区域,而不是整个视图。请执行下列操作:

.background(
    Color.appColor
        .cornerRadius(bottomLeft, corners: .bottomLeft)
        .ignoresSafeArea()
)
// .background(Color.appColor)
// .cornerRadius(bottomLeft, corners: .bottomLeft)
.padding(.bottom, 10)

推荐阅读