SwiftUI:为什么背景超出框架?

SwiftUI: Why the background exceeds the frame?

让我们看一下这个简单的代码:

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

为什么背景超出了框架?然而边框按预期工作:

出于某种原因,Color 已更改为忽略安全 area/frame 约束并向外流动。解决方法是使用彩色形状:

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

默认情况下,后台功能会忽略“安全区域”(在很多情况下这很好)。为了防止这种情况发生,只需写:

.background(.gray, ignoresSafeAreaEdges: [])

更多信息,请访问: https://developer.apple.com/documentation/swiftui/view/background(_:ignoressafeareaedges:)