Properties2
| Type | Idea |
| Note created | Feb 17, 2025 |
When programming with SwiftUI, we have to understand that the order in which we apply modifiers to views does matter. Views are immutable, so a new view is created when the modifier is applied (there is no in-place modification).
Below there is an example of wrong and correct behaviour because of this:
Button("Hello, world!") {
// do nothing
}
.background(.red)
.frame(width: 200, height: 200)This code will generate a 200x200 button that contains a small red rectangle surrounding the text. The red rectangle is not 200x200 because it was generated before the size modification. We can find the code that generates the expected result below.
Button("Hello, world!") {
// do nothing
}
.frame(width: 200, height: 200)
.background(.red)This is, however, not exactly how SwiftUI works - it is just a helpful mental framework to understand certain results.