SwiftUI’s format primitives typically don’t present relative sizing choices, e.g. “make this view 50 % of the width of its container”. Let’s construct our personal!
Use case: chat bubbles
Contemplate this chat dialog view for example of what I wish to construct. The chat bubbles at all times stay 80 % as vast as their container because the view is resized:
Constructing a proportional sizing modifier
1. The Structure
We are able to construct our personal relative sizing modifier on prime of the Structure
protocol. The format multiplies its personal proposed measurement (which it receives from its guardian view) with the given elements for width and top. It then proposes this modified measurement to its solely subview. Right here’s the implementation (the complete code, together with the demo app, is on GitHub):
/// A customized format that proposes a proportion of its
/// acquired proposed measurement to its subview.
///
/// - Precondition: should comprise precisely one subview.
fileprivate struct RelativeSizeLayout: Structure {
var relativeWidth: Double
var relativeHeight: Double
func sizeThatFits(
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()
) -> CGSize {
assert(subviews.rely == 1, "expects a single subview")
let resizedProposal = ProposedViewSize(
width: proposal.width.map { $0 * relativeWidth },
top: proposal.top.map { $0 * relativeHeight }
)
return subviews[0].sizeThatFits(resizedProposal)
}
func placeSubviews(
in bounds: CGRect,
proposal: ProposedViewSize,
subviews: Subviews,
cache: inout ()
) {
assert(subviews.rely == 1, "expects a single subview")
let resizedProposal = ProposedViewSize(
width: proposal.width.map { $0 * relativeWidth },
top: proposal.top.map { $0 * relativeHeight }
)
subviews[0].place(
at: CGPoint(x: bounds.midX, y: bounds.midY),
anchor: .middle,
proposal: resizedProposal
)
}
}
Notes:
-
I made the kind non-public as a result of I wish to management how it may be used. That is essential for sustaining the belief that the format solely ever has a single subview (which makes the mathematics a lot less complicated).
-
Proposed sizes in SwiftUI could be
nil
or infinity in both dimension. Our format passes these particular values by way of unchanged (infinity occasions a proportion continues to be infinity). I’ll talk about under what implications this has for customers of the format.
2. The View extension
Subsequent, we’ll add an extension on View
that makes use of the format we simply wrote. This turns into our public API:
extension View {
/// Proposes a proportion of its acquired proposed measurement to `self`.
public func relativeProposed(width: Double = 1, top: Double = 1) -> some View {
RelativeSizeLayout(relativeWidth: width, relativeHeight: top) {
// Wrap content material view in a container to ensure the format solely
// receives a single subview. As a result of views are lists!
VStack { // alternatively: `_UnaryViewAdaptor(self)`
self
}
}
}
}
Notes:
-
I made a decision to go together with a verbose title,
relativeProposed(width:top:)
, to make the semantics clear: we’re altering the proposed measurement for the subview, which received’t at all times lead to a unique precise measurement. Extra on this under. -
We’re wrapping the subview (
self
within the code above) in aVStack
. This may appear redundant, but it surely’s obligatory to ensure the format solely receives a single factor in its subviews assortment. See Chris Eidhof’s SwiftUI Views are Lists for an evidence.
Utilization
The format code for a single chat bubble within the demo video above seems like this:
let alignment: Alignment = message.sender == .me ? .trailing : .main
chatBubble
.relativeProposed(width: 0.8)
.body(maxWidth: .infinity, alignment: alignment)
The outermost versatile body with maxWidth: .infinity
is chargeable for positioning the chat bubble with main or trailing alignment, relying on who’s talking.
You’ll be able to even add one other body that limits the width to a most, say 400 factors:
let alignment: Alignment = message.sender == .me ? .trailing : .main
chatBubble
.body(maxWidth: 400)
.relativeProposed(width: 0.8)
.body(maxWidth: .infinity, alignment: alignment)
Right here, our relative sizing modifier solely has an impact because the bubbles develop into narrower than 400 factors. In a wider window the width-limiting body takes priority. I like how composable that is!
80 % received’t at all times lead to 80 %
In case you watch the debugging guides I’m drawing within the video above, you’ll discover that the relative sizing modifier by no means stories a width larger than 400, even when the window is vast sufficient:
![A Mac window showing a mockup of a chat conversation with bubbles for the speakers. Overlaid on the chat bubbles are debugging views showing the widths of different components. The total container width is 753. The relW=80% debugging guide shows a width of 400.](https://oleb.net/media/2023-03-23-SwiftUI-relativeWidth-and-maxWidth-1688px.png)
It’s because our format solely adjusts the proposed measurement for its subview however then accepts the subview’s precise measurement as its personal. Since SwiftUI views at all times select their very own measurement (which the guardian can’t override), the subview is free to disregard our proposal. On this instance, the format’s subview is the body(maxWidth: 400)
view, which units its personal width to the proposed width or 400, whichever is smaller.
Understanding the modifier’s habits
Proposed measurement ≠ precise measurement
It’s essential to internalize that the modifier works on the premise of proposed sizes. This implies it relies on the cooperation of its subview to realize its purpose: views that ignore their proposed measurement will likely be unaffected by our modifier. I don’t discover this notably problematic as a result of SwiftUI’s total format system works like this. Finally, SwiftUI views at all times decide their very own measurement, so you may’t write a modifier that “does the precise factor” (no matter that’s) for an arbitrary subview hierarchy.
nil
and infinity
I already talked about one other factor to pay attention to: if the guardian of the relative sizing modifier proposes nil
or .infinity
, the modifier will cross the proposal by way of unchanged. Once more, I don’t suppose that is notably unhealthy, but it surely’s one thing to pay attention to.
Proposing nil
is SwiftUI’s means of telling a view to develop into its ideally suited measurement (fixedSize
does this). Would you ever wish to inform a view to develop into, say, 50 % of its ideally suited width? I’m unsure. Possibly it’d make sense for resizable pictures and comparable views.
By the way in which, you might modify the format to do one thing like this:
- If the proposal is
nil
or infinity, ahead it to the subview unchanged. - Take the reported measurement of the subview as the brand new foundation and apply the scaling elements to that measurement (this nonetheless breaks down if the kid returns infinity).
- Now suggest the scaled measurement to the subview. The subview would possibly reply with a unique precise measurement.
- Return this newest reported measurement as your personal measurement.
This strategy of sending a number of proposals to youngster views is named probing. A number of built-in containers views do that too, e.g. VStack
and HStack
.
Nesting in different container views
The relative sizing modifier interacts in an attention-grabbing means with stack views and different containers that distribute the accessible house amongst their youngsters. I assumed this was such an attention-grabbing matter that I wrote a separate article about it: How the relative measurement modifier interacts with stack views.
The code
The whole code is out there in a Gist on GitHub.
Digression: Proportional sizing in early SwiftUI betas
The very first SwiftUI betas in 2019 did embrace proportional sizing modifiers, however they have been taken out earlier than the ultimate launch. Chris Eidhof preserved a replica of SwiftUI’s “header file” from that point that exhibits their API, together with fairly prolonged documentation.
I don’t know why these modifiers didn’t survive the beta section. The discharge notes from 2019 don’t give a purpose:
The
relativeWidth(_:)
,relativeHeight(_:)
, andrelativeSize(width:top:)
modifiers are deprecated. Use different modifiers likebody(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:)
as an alternative. (51494692)
I additionally don’t keep in mind how these modifiers labored. They in all probability had considerably comparable semantics to my resolution, however I can’t make sure. The doc feedback linked above sound easy (“Units the width of this view to the desired proportion of its guardian’s width.”), however they don’t point out the intricacies of the format algorithm (proposals and responses) in any respect.