How to access safeArea insets while the parent view used IgnoringSafeArea()

2.7k views Asked by At

As you can see the picture I want to place the search bar exactly to the top of the safeArea but the proxy.safeAreaInsets has not the proper value because in the PreviewProvider the parent uses edgesIgnoringSafeArea.

what can I do ? is there any way to access safeAreaInsets?

struct FindView: View {
  
  // MARK: -  Properties
  @ObservedObject var viewModel: FindViewModel
  
  init(viewModel: FindViewModel){
    self.viewModel = viewModel

  }
  
  var body: some View {
 
      GeometryReader { proxy in
        ScrollView(.vertical, showsIndicators: true, content: {
          VStack(alignment: .leading, spacing: 8){
             SearchBar()
              .frame(height: 48, alignment: .center)
              .padding(.all, 16)
              
            
            Text("Categories")
              .multilineTextAlignment(.leading)
              .font(.system(size: 21))
              .padding(.all, 16)
              
          }.frame(width: proxy.size.width)
        })
      }
  }
}

struct FindView_Previews: PreviewProvider {
  static var previews: some View {
    ZStack(alignment: .center, content: {
      Rectangle().foregroundColor(.red)
      FindView(viewModel: FindViewModel())
    }).edgesIgnoringSafeArea(.all)
  }
}

Preview of the code

2

There are 2 answers

0
diogo On

You should apply the .edgesIgnoringSafeArea(.all) only to the rectangle, not to the ZStack. This way, only it should fill the screen, while everything else remains in place.

Then, to make it so that the FindView fills the screen (respecting safe area), you need make its frame extend with .frame(maxWidth: .infinity, maxHeight: .infinity)


Code sample:

struct ContentView: View {
    var body: some View {
        ZStack {
            Rectangle()
                .fill(Color.red)
                .edgesIgnoringSafeArea(.all)
            Text("This should respect the safe area")
                .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
        }
    }
}
0
Mir On

simple way;

     struct test: View {
          var body: some View {
              VStack{
                Text("Your view comes here")
                Spacer()
              }
               .frame(minWidth:0, maxWidth: .infinity, minHeight: 0,maxHeight: .infinity, alignment: .center)
               .padding(.top,UIApplication.shared.windows.first?.safeAreaInsets.top ?? 40)
               .background(Color.red)
               .edgesIgnoringSafeArea(.all)
          }
      }