< How to control layout priority using layoutPriority() | How to create stacks using VStack and HStack > |
Updated for Xcode 12.5
SwiftUI makes it easy to create two views that are the same size, regardless of whether you want the same height or the same width, by combining a frame()
modifier with fixedSize()
– there’s no need for a GeometryReader
or similar.
The key is to give each view you want to size an infinite maximum height or width, which will automatically make it stretch to fill all the available space. You then apply fixedSize()
to the container they are in, which tells SwiftUI those views should only take up the space they need. The result is that SwiftUI figures out the least amount of space the views need, then allows them to take up that full amount – the two views will always match their sizes no matter what they contain.
Here’s an example showing how to make two text views have the same height even though they have very different text lengths. Thanks to the frame()
and fixedSize()
combination both text views are laid out at the same size:
HStack {
Text("This is a short string.")
.padding()
.frame(maxHeight: .infinity)
.background(Color.red)
Text("This is a very long string with lots and lots of text that will definitely run across multiple lines because it's just so long.")
.padding()
.frame(maxHeight: .infinity)
.background(Color.green)
}
.fixedSize(horizontal: false, vertical: true)
This approach works just as well when you want to make two views have the same width:
VStack {
Button("Log in") { }
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.blue)
.clipShape(Capsule())
Button("Reset Password") { }
.foregroundColor(.white)
.padding()
.frame(maxWidth: .infinity)
.background(Color.blue)
.clipShape(Capsule())
}
.fixedSize(horizontal: true, vertical: false)
There are many other significantly more complex solutions to this same problem, which is quite strange given how well the simple solution works for most people. I first learned this solution from Becky Hansmeyer and now I use nothing else!
SPONSORED Emerge helps iOS devs write better, smaller apps by profiling binary size on each pull request and surfacing insights and suggestions. Companies using Emerge have reduced the size of their apps by up to 50% in just the first day. Built by a team with years of experience reducing app size at Airbnb.
Sponsor Hacking with Swift and reach the world's largest Swift community!
Link copied to your pasteboard.