Cequiel
Cequiel

Reputation: 3777

SwiftUI: Why the background exceeds the frame?

Let's have a look at this simple code:

GeometryReader { gr in
    Text("hi there!")
        .frame(width: 2 * gr.size.width / 3, height: gr.size.height)
        .background(.yellow)
        .border(.gray)
}

Why the background exceeds the frame? The border however works as expected:

enter image description here

Upvotes: 1

Views: 563

Answers (2)

Cequiel
Cequiel

Reputation: 3777

By default, the background function ignores the "safe area" (which is good in many cases). To prevent this from happening, simply write:

.background(.gray, ignoresSafeAreaEdges: [])

More info at: https://developer.apple.com/documentation/swiftui/view/background(_:ignoressafeareaedges:)

Upvotes: 4

Yrb
Yrb

Reputation: 9675

For some reason, Color has changed to ignoring safe area/frame constraints and flows outside. The fix is to use a colored shape:

        GeometryReader { gr in
            Text("hi there!")
                .frame(width: 2 * gr.size.width / 3, height: gr.size.height)
                .background(
                    Rectangle()
                        .fill(Color.yellow)
                )
                .border(.gray)
        }

Upvotes: 1

Related Questions