In a radial quick-action menu built with SwiftUI's Layout protocol, how do you give the layout per-button data such as a fixed angle?
answer
- a key with a default
- set by a modifier on the child
- read through the proxy
- like layoutPriority, but yours
basics
~20 sDeclare a LayoutValueKey with a defaultValue, set it on each button with layoutValue(key:value:), usually wrapped in a View extension, and read it inside the layout with subview[Key.self]; buttons that never set it read the default.
solid answer
~40 sA `Layout` method receives the proposal, bounds, subview proxies and cache, with no slot for app data, so per-child data has to travel on the children. `LayoutValueKey` (iOS 16) is the mechanism: a type with a `static let defaultValue`, set on a child with `layoutValue(key:value:)` and read from that child's `LayoutSubview` proxy by subscripting, `subview[ActionAngle.self]`. Wrap the setter in a `View` extension such as `.actionAngle(.degrees(90))` so call sites read naturally. A child that never sets it returns `defaultValue`, so an optional defaulting to `nil` lets the layout fall back to even spacing. It works like the built-in `layoutPriority(_:)`, which the proxy exposes as `priority`. Apple's custom-layout sample uses this pattern to store each pet's rank and rotate a radial layout so the leader sits at the top.
code
swift · 29 linesimport SwiftUI
private struct ActionAngle: LayoutValueKey {
static let defaultValue: Angle? = nil
}
extension View {
func actionAngle(_ angle: Angle) -> some View {
layoutValue(key: ActionAngle.self, value: angle)
}
}
struct RadialMenuLayout: Layout {
var radius: CGFloat = 80
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
proposal.replacingUnspecifiedDimensions()
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
let step = 360.0 / Double(max(subviews.count, 1))
for (index, subview) in subviews.enumerated() {
let angle = subview[ActionAngle.self] ?? .degrees(step * Double(index))
let point = CGPoint(x: bounds.midX + radius * CGFloat(sin(angle.radians)),
y: bounds.midY - radius * CGFloat(cos(angle.radians)))
subview.place(at: point, anchor: .center, proposal: .unspecified)
}
}
}go deeper
Recall that a custom key plus the layoutValue modifier lets each child carry a value its layout can read.
Explain declaring defaultValue, wrapping layoutValue(key:value:) in a View extension, and reading subview[Key.self] inside the layout's methods.
Show why per-child values beat positional arrays when buttons appear conditionally, and how an optional default signals no preference.
Treat each custom key's modifier as public API in a shared library, with a documented name, effect and default.
## The problem: data the layout cannot see A radial quick-action menu places buttons on a circle around a central button: compose, camera, voice note, location. Spacing them evenly is pure arithmetic, 360 degrees divided by the count. Product, though, often wants exceptions: the camera always at the top, the destructive action always at the bottom. That is **per-child data**, and a custom `Layout` has no per-child parameter for it. Its methods receive a `ProposedViewSize`, the `bounds`, a `Subviews` collection of proxies and a cache (plus the guide being asked about in `explicitAlignment`), with no slot for app data. The children are built in view code, so the data has to ride along on the children themselves. ## LayoutValueKey: a custom layout value SwiftUI's answer, available since iOS 16, is **`LayoutValueKey`**. Apple's documentation describes custom values "that you set on individual views, and that your container view can access to guide its layout behavior", resembling built-in layout values such as those set with `layoutPriority(_:)` and `zIndex(_:)`. Three steps: 1. **Declare a key.** A type conforming to `LayoutValueKey` implements one requirement, `static var defaultValue`; its type becomes the key's `Value`. `static let defaultValue: Angle? = nil` makes the value an optional angle. 2. **Set it on a child.** Apply `layoutValue(key:value:)` to the view. A small extension, `func actionAngle(_ angle: Angle) -> some View`, hides the key type and reads like any SwiftUI modifier. 3. **Read it during layout.** Subscript the child's proxy with the key: `subview[ActionAngle.self]`. A view that never set a value returns `defaultValue`. ## Building the radial menu The layout follows Apple's radial example in "Composing custom layouts with SwiftUI": - **Size.** `sizeThatFits` returns `proposal.replacingUnspecifiedDimensions()`, filling whatever space the parent offers. With no argument an unspecified dimension falls back to 10 points, so give the menu a frame. - **Angle.** Each button uses its custom angle when it has one, otherwise its index times the even step. - **Point.** Convert the angle to a point on a circle of the chosen radius around `bounds.midX` and `bounds.midY`. - **Place.** Call `place(at:anchor:proposal:)` with `anchor: .center`, so the button's centre sits on the circle, and a `.unspecified` proposal, so each button takes its ideal size. Apple's sample stores each pet's rank through a `LayoutValueKey` and reads it to compute a rotation offset that puts the leader nearest the top. ## Why not other channels | Mechanism | Direction | Why it does not fit | |---|---|---| | Environment values | from a parent down to descendants | the data comes from each child, not from above | | Preferences | from descendants up to an ancestor's `onPreferenceChange` | delivered to view code, not into the layout's methods | | An array parameter on the layout | from the call site, matched by position | indexes drift when a button is shown conditionally | | `LayoutValueKey` | from each child to its own proxy | travels with the child it describes | The array parameter is the tempting shortcut: `RadialMenuLayout(angles: [...])`, matched by index. It breaks as soon as one button is hidden for a user without permission, because every later button shifts while the array does not. ## Things to get right - **Choose a default that means "no opinion".** An optional with `nil` lets the layout tell "unset" from "set to zero degrees". - **Keep the key private** and expose only the modifier, so the layout's contract is the modifier's name and parameter type. - **The proxy subscript is read-only.** The layout reads the value; it cannot write one back to the child. - **Built-in values have their own properties.** The proxy exposes `layoutPriority(_:)` as `priority` and spacing preferences as `spacing`; custom keys go through the subscript. - **Name the modifier for intent.** `.actionAngle(_:)` tells a reader what the button wants; `layoutValue(key:value:)` repeated at every call site tells them how the layout works, which is the detail a shared component should hide. - **Animate the geometry, not the key.** `Layout` refines `Animatable`, so a layout can expose its radius through `animatableData` for an opening animation; the values on the children only decide where each button sits.
- What happens to the radial menu when one button is shown only conditionally?The layout's subviews collection simply holds one proxy fewer, and every remaining button still carries its own value, so a pinned angle stays pinned. Evenly spaced buttons recompute the step from the new count. A positional array of angles on the layout would instead shift every later button by one slot.
- Can a layout read built-in layout values the same way?Partly. The proxy exposes the value of `layoutPriority(_:)` as `subview.priority` and the view's spacing preferences as `subview.spacing`. It has no property for `zIndex(_:)`, which governs drawing order rather than placement, so a layout that needs ordering data of its own defines a custom key.
- Preferences set on each button arrive inside placeSubviews.
- Reading a LayoutValueKey that a child never set crashes the layout.
- A parallel array of angles on the layout is as safe as a value on each child.
- LayoutValueKey needs iOS 17 or later.
- The layout can write a value back to a child through the proxy subscript.