Johnas
Johnas

Reputation: 326

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.

Upvotes: 0

Views: 1438

Answers (2)

Ayoub Nouri
Ayoub Nouri

Reputation: 201

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

Upvotes: 1

Dilan
Dilan

Reputation: 2688

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()
        }
    }
}

Result in canvas preview

Upvotes: 1

Related Questions