简体   繁体   中英

Move VStack at the top of the page swiftUI

I want to create a top bar and my code looks like this:

struct MyView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Bar()
            Spacer()
        }
    }
}

struct Bar: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            HStack {
                Spacer()
                Text("Community").comfortaa(weight: .bold, size: 20).foregroundColor(.therameBlack)
                Spacer()
                Button(action: {
                }) {
                    Image(systemName: "gearshape.fill").font(.headline).foregroundColor(.therameBlack)
                }
            }
        }.padding(.leading,5).padding(.trailing,5)
        .padding(.top,(UIApplication.shared.windows.last?.safeAreaInsets.top)! + 10)
    }
}

However there is still spacing at the top of the screen:

I also tried to do this, as suggested in this post How to move vstack at top of the screen in swiftui?

struct MyView: View {
    var body: some View {
        VStack {
            VStack(alignment: .leading) {
                TopBar()
                Spacer()
            }
            Spacer()
        }
    }
}

but it didn't help... Also if I delete the +10 from the.safeAreaInsets there is still space at the top.

May Be padding is the issue. Just remove complex paddings and add the simple padding.

struct TestView: View {
    var body: some View {
        VStack(alignment: .leading) {
            Bar()
            Spacer()
        }
    }
}


struct Bar: View {
    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            HStack {
                Spacer()
                Text("Community")
                Spacer()
                Button(action: {
                }) {
                    Image(systemName: "gearshape.fill").font(.headline)
                }
            }.padding()
        }
    }
}

结果画布预览

I think if you remove .padding(.top,(UIApplication.shared.windows.last?.safeAreaInsets.top)! + 10) it will be aligned on the top of the screen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM