How to adjust the size of a view relative to its container
How to adjust the size of a view relative to its container 관련
Updated for Xcode 15
New in iOS 17
SwiftUI's containerRelativeFrame()
is a simple but powerful way to make views have a size relative to their container, which might be their whole window, the scroll view they are inside, or even just one column in your layout.
There are three core values you need to provide it: which axis you're trying to set, how many parts you want to divide the space into, and also how many parts should be given to each view.
For example, this tells views inside a ScrollView
that they should be 2/5ths the width of their container:
ScrollView(.horizontal, showsIndicators: false) {
HStack {
ForEach(0..<10) { i in
Text("Item \(i)")
.foregroundStyle(.white)
.containerRelativeFrame(.horizontal, count: 5, span: 2, spacing: 10)
.background(.blue)
}
}
}
To be clear: the count
parameter refers to how many parts the scroll view's horizontal space should be split into, and the span
parameter refers to how many parts should be allocated to each text view. We've used 5 for count
, meaning that the scroll view's horizontal space will be split into 5, then used 2 for span
, meaning that each text view will be given 2/5ths of the space.
This kind of uneven span means users will see 2.5 views when the app runs – they see two things immediately, then see just enough of the next thing to know that scrolling is possible.
Exactly how you divide your space is down to you, but using a count of 12 is common in websites because it's divisible by 1, 2, 3, 4, 6, and 12, giving you lots of flexibility.
There are two extra things to know about using container relative frames:
- You can provide more than one axis if you want, using
[.horizontal, .vertical]
. - The default alignment is
.center
, but you can specify a customalignment
parameter with whatever you want.