Duck
Duck

Reputation: 35933

How to solve this top bar problem on SwiftUI, elegantly?

I am trying to use the whole iPhone area for my app.

I have this HStack at the top, used to create a custom toolbar.

var body: some View {

  VStack (spacing:0) {
  
    MyTopbar()
    // other controls

    Spacer()
  }
  .edgesIgnoringSafeArea(.top)

This appears like this on new devices with a notch and old devices without a notch. The notch cuts my menu.

enter image description here

I can solve that by adding a spacer with a frame height before MyTopbar() on the vertical stack but first of all this seems to be a very awful solution. First I have to guess a height for that spacer. Then I have to detect if the device has a notch or not (?).

Is there a better way?

Upvotes: 0

Views: 569

Answers (2)

Alladinian
Alladinian

Reputation: 35616

You can think of it as layers (content that respects safe area and content that doesn't).

Something like this perhaps:

struct ContentView: View {
    var body: some View {
        ZStack {
            Color.blue.ignoresSafeArea() // Whatever view fills the whole screen

            VStack (spacing:0) {
                MyTopbar()
                // other controls
                Spacer()
            }
        }
    }
}

enter image description here

Upvotes: 3

Raja Kishan
Raja Kishan

Reputation: 18904

A possible solution to add clear color with safe area height. No need for much calculation.

var body: some View {

  VStack (spacing:0) {
    Color.clear.frame(height: Color.clear.frame(height: UIApplication.shared.windows.first?.safeAreaInsets.top ?? 0)
    MyTopbar()
    // other controls

    Spacer()
  }
  .edgesIgnoringSafeArea(.top)

Upvotes: 1

Related Questions