'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



Solution 1:[1]

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:)

Solution 2:[2]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Cequiel
Solution 2 Yrb