Auto Layout vs. Manual Layout for Dynamic Type Support in Custom UI Elements
29K reputation · 03 Oct 2024, 00:35 UTC
Auto Layout vs. Manual Layout for Dynamic Type Support in Custom UI Elements
Goal: Make a custom component adjust its size and content when the user changes the system font size via Dynamic Type. The component contains multiple labels and icons that must remain legible and properly spaced.
Constraint: Auto Layout automatically respects intrinsicContentSize and UIContentSizeCategoryDidChangeNotification, but can cause layout thrashing if the constraint graph is large. Manual layout in layoutSubviews gives fine‑grained control and can be optimized, yet it requires careful recalculation of frames and can drift if font metrics are not updated.
Unresolved Decision: Which method balances performance, maintainability, and accessibility consistency for a component with dozens of subviews?
Specific Questions:
- For a view with 30 labels, which approach yields lower CPU usage during a Dynamic Type change?
- When using manual layout, what is the best practice to update
accessibilityElementsso VoiceOver reflects the new geometry? - Does Auto Layout provide any guarantees about preserving
accessibilityTraitsacross font size changes?
1 answer
1 question comment
Use comments to ask for clarification. Post a solution as an answer.
29,025 reputation · 03 Oct 2024, 06:06 UTC
While manual layout optimizes CPU usage for high-density views, it introduces a critical requirement for accessibility: updating the accessibility frame. Unlike Auto Layout, which automatically synchronizes the accessibility engine with the constraint solver, manual frame updates in layoutSubviews do not always trigger an immediate update of the accessibilityFrame for all subviews.
To ensure VoiceOver accurately reflects the new geometry after a Dynamic Type change, verify the following implementation details:
- Frame Synchronization: Ensure that
isAccessibilityElementis set correctly. If the custom component acts as a container, theaccessibilityFrameof the parent must be recalculated to encompass the new boundaries of its expanded children. - Notification Timing: When calling
setNeedsLayout()in response toUIContentSizeCategoryDidChange, the accessibility tree may lag. In complex manual layouts, explicitly callingUIAccessibility.post(notification: .layoutChanged, argument: nil)after the layout pass ensures the screen reader recognizes the new element positions.