UIStackView Tutorial: A Comprehensive Guide to iOS Linear Layout
This tutorial explains UIStackView, Apple’s iOS 9 linear layout container that mirrors Flexbox concepts, covering axis, distribution, alignment, and spacing, showing how to add arranged subviews, hide them dynamically, adjust hugging and compression priorities, and noting its limitations such as lacking order, flex‑grow, and flex‑basis controls.
This article provides a comprehensive guide to UIStackView , Apple's linear layout container introduced in iOS 9 within the UIKit framework. The tutorial begins by explaining the technical background, drawing parallels to web Flex layout concepts such as flex-direction , flex-wrap , justify-content , align-items , and align-content .
UIStackView adopts Flex's layout philosophy, providing a linear arrangement approach for organizing subviews with minimal code. It serves as a container that manages the layout of its arranged subviews without directly participating in screen rendering—note that overriding drawRect: has no effect.
The core parameters covered include: Axis ( horizontal / vertical ), Distribution ( fill , fillEqually , fillProportionally , equalSpacing , equalCentering ), Alignment ( fill , top , center , bottom , firstBaseline , lastBaseline , trailing , leading ), and spacing for controlling the minimum distance between subviews.
Basic usage involves adding subviews via addArrangedSubview: rather than addSubview: . The article demonstrates a practical example with two UILabels and a separator line centered together.
Advanced features include hiding subviews dynamically (which removes them from the layout calculation) and managing content hugging/compression resistance priorities using setContentHuggingPriority:forAxis: and setContentCompressionResistancePriority:forAxis: to control how subviews stretch or compress.
The article concludes by noting UIStackView 's limitations compared to Flex layout—specifically the inability to individually control properties like order , flex-grow , and flex-basis on subviews.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.