简体   繁体   中英

SwiftUI: How to know correct order of modifiers?

I'm pretty new to SwiftUI , learning it for the first time, and couldn't understand why the below snippet doesn't work. Ideally, the VStack should stretch in all directions and the Image should have a width of 200px without losing its aspect ratio.

Code

struct ContentView: View {
    var body: some View {
        VStack() {
            Image("Image Name")
                .resizable()
                .frame(width: 200)
                .aspectRatio(contentMode: .fit)
        }
        .background(Color.red)
        .frame(maxWidth: .infinity,maxHeight: .infinity)
    }
}

After I accidentally reordered the modifiers , it worked. So, how am I supposed to know the correct order of modifiers without a hit and trial method each time?

// new VStack modifier order 
.frame(maxWidth: .infinity, maxHeight: .infinity)
.background(Color.red)

// new Image modifier order
.resizable()
.aspectRatio(contentMode: .fit)
.frame(width: 200)

The best way to think about it for now is to imagine that SwiftUI renders your view after every single modifier. So, as soon as you say .background(Color.red) it colors the background in red, regardless of what frame you give it. If you then later expand the frame, it won't magically redraw the background – that was already applied.

Of course, this isn't actually how SwiftUI works, because if it did it would be a performance nightmare, but it's a neat mental shortcut to use while you're learning.

Please refer to this link for more details https://www.hackingwithswift.com/books/ios-swiftui/why-modifier-order-matters#:~:text=Every%20time%20we%20modify%20a,up%3A%20ModifiedContent%3CModifiedContent%3C%E2%80%A6

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM