Ocean1878
Ocean1878

Reputation: 23

Ignore Safe Area in Xcode with SwiftUI

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

Upvotes: 2

Views: 4687

Answers (3)

Alex
Alex

Reputation: 120

I had the same problem. Turned out to be a (wrong) setting in my Xcode project (still not sure which one). I had to start a new Xcode project and moved all the source code and asset files into that new project and the problem was solved.

Upvotes: 0

Jamesnjones
Jamesnjones

Reputation: 41

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!")
        }
    
 }
}

Upvotes: 0

ScottM
ScottM

Reputation: 10404

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.

Upvotes: 6

Related Questions