Home > Mobile >  SwiftUI why the background not cover all frames when background modifier before frame?
SwiftUI why the background not cover all frames when background modifier before frame?

Time:09-18

Text("Hello world!")
    .background(.cyan)
    .frame(width: 200, height: 200)
    .border(Color.blue, width: 1)
Text("Hello world!")
    .frame(width: 200, height: 200)
    .background(.cyan)
Rectangle()
    .fill(.cyan)
    .frame(width: 200, height: 200)
    .border(Color.blue, width: 1)

The code result:

result

Why the order matters? And why the Rectangle().fill() not the same?

CodePudding user response:

In SwiftUI, each modifier takes the view it's attached to, changes it, and passes on the changed view onto the next modifier in the chain.

The modifiers .background and .overlay allow us to add other views below or on top of our original view, but don't affect the sizing decisions when it comes to layout.

In contrast, .frame alters the layout, but otherwise doesn't really change the way the view it's modifying is rendered.

So in the first example:

  • We start with a Text view that is large enough to fit the text in, and no more.
  • The background is applied to that view, going only up to the extents determined by the original view.
  • The frame is resized, with the original contents centered in the new view.
  • A border is applied to the new, larger frame.

In the second:

  • We start with a Text view that is large enough to fit the text in, and no more.
  • The frame is resized, with the original contents centered in the new view.
  • The background is applied to that view, filling the frame as defined in the previous step.

In the third, Rectangle and other objects that conform to the Shape protocol have no intrinsic size of their own. Unlike Text objects, which set the frame to be as small as possible, a Shape's initial frame will be as large as it possibly can be.

So in this case:

  • We define a Rectangle shape, whose initial size is not constrained
  • We set the rectangle's fill colour, which doesn't affect the frame
  • We then set a frame size, which sets constraints on the rectangle.

Hopefully, you can begin to see why order matters and the thought process you can go through to visualise what order your own modifiers need to be in.

  • Related