Home > OS >  Why does color modifier order affect View size in SwiftUI?
Why does color modifier order affect View size in SwiftUI?

Time:05-05

Why does SwiftUI render these two buttons differently?

Trying them one at a time (only 1 button in the body) gives full screen yellow for one and a normal size button for the other.

Test 1

Button("Smh...") {}
    .background(.yellow)
    .frame(maxWidth: .infinity, maxHeight: .infinity)

Test 2

Button("Smh...") {}
    .frame(maxWidth: .infinity, maxHeight: .infinity)
    .background(.yellow)

I could guess why order might matter if the chained methods both modified the layout, but it's not obvious how color would cause this.

CodePudding user response:

The reason is very well explained in this article. Whenever a modifier is applied, a new view is created. In your case:

Test 1:

  1. You create a button with a size dictated by the label
  2. A new view is created with a yellow background
  3. A new view with max width and max height is created, but the yellow background is not applied again, therefore you see a "normal" sized button.

Test 2:

  1. You create a button with a size dictated by the label
  2. A new view is created with max width and height
  3. You then apply the background color, therefore the newly created full screen view has a yellow background

To better understand what I mean, try this on an empty playground:

  import Foundation
  import SwiftUI
  import PlaygroundSupport

  struct ContentView: View {
    var body: some View {
        HStack {
            Button("Smh...") {}
                .frame(width: 100, height: 100)
                .background(.yellow)
        
            Button("Smh...") {}
                .background(.yellow)
                .frame(width: 100, height: 100)
                .border(.green)
                
        }
      }
  }

  PlaygroundPage.current.setLiveView(ContentView())
  • Related