Help, my button is bleeding!
Posted: | Author: Jörn | Filed under: iOS, Swift, SwiftUI | Tags: Button, SwiftUI | No Comments »Recently I was confronted with a strange behaviour of a Button in SwiftUI. The button was placed directly at the top of a view that was at the border to the top of the screen near the status bar. Somehow the button’s background color was stretched all the way to the top. In other words: the buttons background color was underneath the status bar, but the button was not.
struct ContentView: View {
var body: some View {
VStack {
Button(action: {}) {
Image(systemName: "play.fill")
.frame(width: 80, height: 80)
.background(Color.orange)
.border(Color.red, width: 5)
}
Spacer()
}
}
}
Which gives you this:

As you can see, the background color is stretched to the top under the status bar and magic island. Strangely the border is not.
There are use cases where this behaviour is wanted (like extending the background color of a view into the safe area). But for this button it is definitely not wanted. The fix to this is really easy. The .background modifier has a second parameter ignoresSafeAreaEdges that takes a Edge.Set value. The default value for this parameter is .all which extends the background into all safe areas. If you pass an empty Set you can stop the bleeding 😉
struct ContentView: View {
var body: some View {
VStack {
Button(action: {}) {
Image(systemName: "play.fill")
.frame(width: 80, height: 80)
.background(Color.orange, ignoresSafeAreaEdges: [])
.border(Color.red, width: 5)
}
Spacer()
}
}
}
