Home > Enterprise >  Ignore Safe Area in Xcode with SwiftUI
Ignore Safe Area in Xcode with SwiftUI

Time:01-13

With the following code, the safe area is ignored even though no (.edgesIgnoringSafeArea(.all)) is set. Why? How I can reset it or is it a bug?

enter image description here

    struct SafeAreaBootcamp: View {
    var body: some View {
        Text("Hello, World!")
            .frame(maxWidth: .infinity, maxHeight: .infinity)
            .background(Color.red)
    }
}

struct SafeAreaBootcamp_Previews: PreviewProvider {
    static var previews: some View {
        SafeAreaBootcamp()
    }
}

CodePudding user response:

background ignores safe area insets by default – so although the frame or your text view is inset from the top and bottom of an iPhone view, the background will automatically extend into it.

You could elect to use a ZStack to manually layer your view on top of a view that would act as its background. That view wouldn't automatically extend into the safe area, so it'd get you the effect you want.

However, it's possible (and probably preferable) to stick with the background modifier, and tell it not to ignore safe edges. From the documentation:

By default, the background ignores safe area insets on all edges, but you can provide a specific set of edges to ignore, or an empty set to respect safe area insets on all edges:

Rectangle()
  .background(
    .regularMaterial,
    ignoresSafeAreaEdges: []) // Ignore no safe area insets.

Note that this constructor only works with a subset of backgrounds – colors, materials, etc. – that conform to the ShapeStyle protocol. That's explained in the doc page but it's worth repeating.

CodePudding user response:

I would use a zStack, one of the issues with your current code is using the frame(maxHeight : .infinity) you're forcing the view to extend vertically for the entire screen. Below code is a cleaner way to write what you're after.

 struct ContentView: View {

var body: some View {
        ZStack {
        Color.red
    Text("Hello, World!")
        }
    
 }
}
  •  Tags:  
  • Related