In SwiftUI, prefer Spacer or .frame?

I found that, in most cases, the layout behavior using Spacer can be replaced with .frame(maxWidth:, alignment:) (or height) seamlessly. For example:

HStack {
    Text("Plane")
    Spacer(minLength: 0)
    Image(systemName: "paperplane")
}

can be replaced with

HStack {
    Text("Plane")
        .frame(maxWidth: .infinity, alignment: .leading)
    Image(systemName: "paperplane")
}
HStack {
    Spacer()
    Text("Plane")
    Spacer()
}

can be replace with

Text("Plane").frame(maxWidth: .infinity, alignment: .center)
// even HStack is unneeded 

What I care about is that, since Spacer is an actual View that is arranged within the view hierarchy, using Spacer will consume more memory and cpu resources than not using it. Consider the following two views:

ScrollView {
    VStack(spacing: 0) {
        ForEach(1..<10000) {
            HStack {
                Spacer(minLength: 0)
                Text(String($0))
                Spacer(minLength: 0)
            }
        }
    }
}

and

ScrollView {
    VStack(spacing: 0) {
        ForEach(1..<10000) {
            Text(String($0))
                .frame(width:.infinity, alignment: .center)
        }
    }
}

The former will consume about 100MB more memory and render a little slower than the latter.

So, as the official SwiftUI tutorial is using Spacer widely, I wonder which one is preferred to use?

Terms of Service

Privacy Policy

Cookie Policy