SwiftUI’s Unexpected Behaviours - A Case Study on Padding and Backgrounds
Many developers complain about SwiftUI because some of its behaviours feel counter-intuitive. For example, in the code at #1, if you comment out the .padding() modifier, the entire area above the search field turns red. That happens because the background of the search view bleeds into its parent container. If you don’t want the Search view’s background to affect the parent view, you have to break that view hierarchy connection.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var body: some View {
VStack(spacing: 24) {
search
Spacer()
}
// .padding() // #1
.background(ThoughtStreamAsset.Colors.bgPrimary.swiftUIColor)
}
var search: some View {
TextField("Search", text: $searchText, prompt: Text("Search your knowledge base").foregroundColor(.gray))
.foregroundColor(ThoughtStreamAsset.Colors.textPrimary.swiftUIColor)
.padding()
.background(Color.red)
}When the padding at #1 is not commented out, the layout renders as expected:
But when you remove the parent padding, SwiftUI changes how the backgroud is applied, causing the red search background to expand and cover areas you wouldn’t expect. These kinds of layout propagation rules are often why developers find SwiftUI unintuitive.