Working with percentages in SwiftUI format – Ole Begemann


SwiftUI’s format primitives usually 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

Take into account this chat dialog view for instance of what I need to construct. The chat bubbles all the time stay 80 % as huge as their container because the view is resized:

The chat bubbles ought to grow to be 80 % as huge as their container. Obtain video

Constructing a proportional sizing modifier

1. The Format

We will construct our personal relative sizing modifier on prime of the Format protocol. The format multiplies its personal proposed dimension (which it receives from its guardian view) with the given components for width and peak. It then proposes this modified dimension to its solely subview. Right here’s the implementation (the total code, together with the demo app, is on GitHub):

/// A customized format that proposes a share of its
/// obtained proposed dimension to its subview.
///
/// - Precondition: should include precisely one subview.
fileprivate struct RelativeSizeLayout: Format {
    var relativeWidth: Double
    var relativeHeight: Double

    func sizeThatFits(
        proposal: ProposedViewSize, 
        subviews: Subviews, 
        cache: inout ()
    ) -> CGSize {
        assert(subviews.depend == 1, "expects a single subview")
        let resizedProposal = ProposedViewSize(
            width: proposal.width.map { $0 * relativeWidth },
            peak: proposal.peak.map { $0 * relativeHeight }
        )
        return subviews[0].sizeThatFits(resizedProposal)
    }

    func placeSubviews(
        in bounds: CGRect, 
        proposal: ProposedViewSize, 
        subviews: Subviews, 
        cache: inout ()
    ) {
        assert(subviews.depend == 1, "expects a single subview")
        let resizedProposal = ProposedViewSize(
            width: proposal.width.map { $0 * relativeWidth },
            peak: proposal.peak.map { $0 * relativeHeight }
        )
        subviews[0].place(
            at: CGPoint(x: bounds.midX, y: bounds.midY), 
            anchor: .middle, 
            proposal: resizedProposal
        )
    }
}

Notes:

  • I made the sort personal as a result of I need to management how it may be used. That is vital for sustaining the idea that the format solely ever has a single subview (which makes the mathematics a lot easier).

  • Proposed sizes in SwiftUI could be nil or infinity in both dimension. Our format passes these particular values via unchanged (infinity instances a share remains to be infinity). I’ll talk about beneath 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 share of its obtained proposed dimension to `self`.
    public func relativeProposed(width: Double = 1, peak: Double = 1) -> some View {
        RelativeSizeLayout(relativeWidth: width, relativeHeight: peak) {
            // 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:peak:), to make the semantics clear: we’re altering the proposed dimension for the subview, which gained’t all the time end in a unique precise dimension. Extra on this beneath.

  • We’re wrapping the subview (self within the code above) in a VStack. This may appear redundant, but it surely’s obligatory to ensure the format solely receives a single ingredient 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 appears 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 accountable for positioning the chat bubble with main or trailing alignment, relying on who’s talking.

You may 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 grow to be narrower than 400 factors. In a wider window the width-limiting body takes priority. I like how composable that is!

80 % gained’t all the time end in 80 %

If you happen to watch the debugging guides I’m drawing within the video above, you’ll discover that the relative sizing modifier by no means studies a width better than 400, even when the window is huge sufficient:


Working with percentages in SwiftUI format – Ole Begemann
The relative sizing modifier accepts the precise dimension of its subview as its personal dimension.

It is because our format solely adjusts the proposed dimension for its subview however then accepts the subview’s precise dimension as its personal. Since SwiftUI views all the time select their very own dimension (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 dimension ≠ precise dimension

It’s vital to internalize that the modifier works on the premise of proposed sizes. This implies it relies on the cooperation of its subview to attain its objective: views that ignore their proposed dimension will likely be unaffected by our modifier. I don’t discover this notably problematic as a result of SwiftUI’s whole format system works like this. In the end, SwiftUI views all the time decide their very own dimension, so you’ll be able to’t write a modifier that “does the correct 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 go the proposal via unchanged. Once more, I don’t assume that is notably unhealthy, but it surely’s one thing to pay attention to.

Proposing nil is SwiftUI’s method of telling a view to grow to be its very best dimension (fixedSize does this). Would you ever need to inform a view to grow to be, say, 50 % of its very best width? I’m undecided. Possibly it’d make sense for resizable photographs and comparable views.

By the way in which, you may modify the format to do one thing like this:

  1. If the proposal is nil or infinity, ahead it to the subview unchanged.
  2. Take the reported dimension of the subview as the brand new foundation and apply the scaling components to that dimension (this nonetheless breaks down if the kid returns infinity).
  3. Now suggest the scaled dimension to the subview. The subview would possibly reply with a unique precise dimension.
  4. Return this newest reported dimension as your individual dimension.

This strategy of sending a number of proposals to baby views is named probing. Plenty 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 fascinating method with stack views and different containers that distribute the accessible house amongst their youngsters. I believed this was such an fascinating matter that I wrote a separate article about it: How the relative dimension 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 had 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 part. The discharge notes from 2019 don’t give a motive:

The relativeWidth(_:), relativeHeight(_:), and relativeSize(width:peak:) modifiers are deprecated. Use different modifiers like body(minWidth:idealWidth:maxWidth:minHeight:idealHeight:maxHeight:alignment:) as a substitute. (51494692)

I additionally don’t bear in mind how these modifiers labored. They in all probability had considerably comparable semantics to my answer, however I can’t be certain. The doc feedback linked above sound easy (“Units the width of this view to the required proportion of its guardian’s width.”), however they don’t point out the intricacies of the format algorithm (proposals and responses) in any respect.

containerRelativeFrame

Replace Could 1, 2024: Apple launched the containerRelativeFrame modifier for its 2023 OSes (iOS 17/macOS 14). In case your deployment goal permits it, this is usually a good, built-in different.

Notice that containerRelativeFrame behaves otherwise than my relativeProposed modifier because it computes the scale relative to the closest container view, whereas my modifier makes use of its proposed dimension because the reference. The SwiftUI documentation considerably vaguely lists the views that depend as a container for containerRelativeFrame. Notably, stack views don’t depend!

Try Jordan Morgan’s article Modifier Monday: .containerRelativeFrame(_ axes:) (2022-06-26) to be taught extra about containerRelativeFrame.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles