An alternative to UIStackView for common Auto Layout patterns.

Related tags

UI StackLayout
Overview

StackLayout

Version License Platform

StackLayout builds on Auto Layout to make some of the most common layouts easier to manage. It creates the constraints that you need and allows you to edit them with semantic method names, like setTopMargin: or setHorizontalAlignment:. It is similar to UIStackView, but unlike UIStackView it is not a subclass of UIView. It is a layout manager you can use with any view. This has a few advantages:

  • Multiple layouts in one view.
  • Less wrapper views in your layout.
  • Compatible with iOS 8+

Basics

Three labels stacked vertically, hugging the top, with a space between them.

let verticalLayout = container.addSubviewsWithVerticalLayout([headerLabel, subtitleLabel, bodyLabel]) { layout in
    layout.verticalAlignment = .Top
    layout.horizontalAlignment = .Fill
}

The above layout takes about 10 constraints usually, which can be a hassle to manage. The layout object manages them for you and allows you to easily change them later. You don't need to keep a reference to the layout object if you don't need it though.

More examples

WelcomeTipLayout

tipView.addSubviewsWithVerticalLayout([titleLabel, bodyLabel, tipsButton, laterButton]) { layout in
    layout.verticalAlignment = .Fill
    layout.verticalMargins = 46
    layout.topMargin = 34
    layout.bottomMargin = 17
    layout.spacing = 28
	layout.setSpacing(10, between: titleLabel, and: bodyLabel)
}

// Constrain the width of the tip view so the text will wrap.
tipView.widthAnchor.constraintEqualToConstant(290).active = true

ToolbarLayout

toolbar.addSubviewsWithHorizontalLayout([trashButton]) { layout in
    layout.horizontalAlignment = .Leading
    layout.verticalAlignment = .Center
    layout.leadingMargin = 15
}

toolbar.addSubviewsWithHorizontalLayout([resizeButton, spotlightButton]) { layout in
    layout.verticalAlignment = .Center
    layout.horizontalAlignment = .Center
}

Most used properties

spacing

setSpacing:betweenView:andView:

(vertical)(horizontal)Alignment

(vertical)(horizontal)Margins

(top)(bottom)(leading)(horizontal)Margin

Alignment

You usually want to choose both a vertical and horizontal alignment.

  • SLAlignmentFill
    • Use this when you want the subviews to completely fill the container (exluding space for margins). This can also make the container shrink until it is just big enough to hold the subviews. This is the most common alignment.
  • SLAlignmentTop/Bottom/Leading/Trailing
    • Just as it sounds. The view(s) will be stuck to the margin of the container view.
  • SLAlignmentCenter
    • This pulls the views to the middle. The layout might create invisible "helper" views to accomplish this. You can control the strength of the centering constraints using centeringPriority.
  • SLAlignmentNone
    • This is the default. Without an alignment the views can be layed out anywhere within the margins of the container. This is only useful when you want to align the views relative to something else in the view hierarchy.

Spacing

All ajdacent subviews have a "space" constraint for the space between them. In the Auto Layout Visual Format Language, it looks like "[first]-space-[second]". By default, this space is set to 0 so all subviews are edge-to-edge. You can set the space between two adjacent subviews by calling setSpacing:betweenView:andView:. You can also adjust the spacing constraints at once by setting spacing, which will override any other previous setSpacing:betweenView:andView: calls.

Spacing constraints are required by default, but can be weakened by setting spacingPriority.

Rules to Remember

If you are working with a layout where these rules are getting in the way, don't be afraid to just ditch Stack Layout and make the constraints yourself! PureLayout or NSLayoutAnchor (iOS 9+) make this easier.

Set both vertical and horizontal alignments

If you don't set an aligment, there are many places a subview can end up. In this layout: container.addSubviewsWithVerticalLayout([redButton, blueButton]), the red and blue button stack can be in the top-left or bottom-right (or anywhere in between) of the container. This can be useful if you want views to be layed out relative to another view in the hierarchy. Generally though, you want to set both verticalAligment and horizontalAlignment.

Subviews stay within margins

Subviews usually stay entirely within the bounds of the containing view, even if there is no vertical or horizontal alignment set. This is done by the "margin" constraints. You can override this by setting the margins to a negative number or reducing the priority of the margin constraints by setting marginsPriority.

Subviews need sizing constraints

StackLayout doesn't govern how big subviews are relative to each other. For example, this layout is ambiguous:

container.addSubviewsWithVerticalLayout([redView, blueView]) { layout in
    layout.verticalAlignment = .Fill
    layout.horizontalAlignment = .Fill
}

Together, redView and blueView fill the container but you need another constraint to say how big they are relative to each other. To make them each take up half of the container you'd need this supplemental constraint: [redView.heightAnchor constraintEqualToAnchor:blueView.heightAnchor].active = YES;

Often subviews already have their own size, either from intrinsicContentSize or from their own subviews and contraints.

Example Project

The example project has not been built yet. If you'd like to contribute, you can build examples in the example project.

Clone the repo, and run pod install from the Example directory first.

Requirements

Installation

StackLayout is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod "StackLayout"

Author

Bridger Maxwell, [email protected]

License

StackLayout is available under the MIT license. See the LICENSE file for more info.

You might also like...
This app presents few examples for common patterns using purer SwiftUI code

VIPERtoSwiftUI GOAL This app presents few examples for common patterns using purer (from authors experience) SwiftUI code. LITERATURE https://www.appy

Auto Layout (and manual layout) in one line.
Auto Layout (and manual layout) in one line.

Auto Layout (and manual layout) in one line. Quick Look view.bb.centerX().below(view2).size(100) It’s equivalent to iOS 9 API: view.centerXAnchor.cons

Auto Layout made easy with the Custom Layout.
Auto Layout made easy with the Custom Layout.

Auto Layout made easy with the Custom Layout. Getting started CocoaPods CocoaPods is a dependency manager for Cocoa projects. You can install it with

🔄 GravitySlider is a beautiful alternative to the standard UICollectionView flow layout.
🔄 GravitySlider is a beautiful alternative to the standard UICollectionView flow layout.

GravitySliderFlowLayout Made by Applikey Solutions Find this project on Dribbble Table of Contents Purpose Supported OS & SDK Versions Installation Us

An alternative layout system for iOS

GranadaLayout GranadaLayout is an alternative layout system for iOS, inspired on the Android layout system. It includes relative and linear layout sys

A controller that uses a UIStackView and view controller composition to display content in a list
A controller that uses a UIStackView and view controller composition to display content in a list

StackViewController Overview StackViewController is a Swift framework that simplifies the process of building forms and other static content using UIS

UIStackView replica for iOS 7.x and iOS 8.x
UIStackView replica for iOS 7.x and iOS 8.x

TZStackView A wonderful layout component called the UIStackView was introduced with iOS 9. With this component it is really easy to layout components

A micro UIStackView convenience API inspired by SwiftUI
A micro UIStackView convenience API inspired by SwiftUI

Stacks A micro UIStackView convenience API inspired by SwiftUI. let stack: UIView = .hStack(alignment: .center, margins: .all(16), [ .vStack(spaci

UICollectionView and UIStackView Homework
UICollectionView and UIStackView Homework

UICollectionView and UIStackView Homework Use one outer StackView containing one CollectionView on top and a horizontal StackView at the bottom with t

Porting UIStackView to iOS 7+
Porting UIStackView to iOS 7+

OAStackView iOS 9 introduced the very cool UIStackView, UIStackView can be used to easily create simple and complex layouts. As expected UIStackView c

CalendarApp Swift - Made a calendar app in swift, completely from scratch using UIStackView and UICollectionView
CalendarApp Swift - Made a calendar app in swift, completely from scratch using UIStackView and UICollectionView

CalendarApp_Swift Made a calendar app in swift, completely from scratch using UI

A data-driven UIScrollView + UIStackView framework for building fast and flexible lists
A data-driven UIScrollView + UIStackView framework for building fast and flexible lists

JKListKit A data-driven UIScrollView + UIStackView framework for building fast and flexible lists. Full Oficial documentation Main Features 🙅 Create

Fast Swift Views layouting without auto layout. No magic, pure code, full control and blazing fast. Concise syntax, intuitive, readable & chainable. [iOS/macOS/tvOS/CALayer]
Fast Swift Views layouting without auto layout. No magic, pure code, full control and blazing fast. Concise syntax, intuitive, readable & chainable. [iOS/macOS/tvOS/CALayer]

Extremely Fast views layouting without auto layout. No magic, pure code, full control and blazing fast. Concise syntax, intuitive, readable & chainabl

A declarative Auto Layout DSL for Swift :iphone::triangular_ruler:
A declarative Auto Layout DSL for Swift :iphone::triangular_ruler:

Cartography 📱 📐 Using Cartography, you can set up your Auto Layout constraints in declarative code and without any stringly typing! In short, it all

Auto Layout made easy
Auto Layout made easy

EasyPeasy is a Swift framework that lets you create Auto Layout constraints programmatically without headaches and never ending boilerplate code. Besi

Lightweight Swift framework for Apple's Auto-Layout
Lightweight Swift framework for Apple's Auto-Layout

I am glad to share with you a lightweight Swift framework for Apple's Auto-Layout. It helps you write readable and compact UI code using simple API. A

An Impressive Auto Layout DSL for  iOS, tvOS & OSX. & It is written in pure swift.
An Impressive Auto Layout DSL for iOS, tvOS & OSX. & It is written in pure swift.

KVConstraintKit KVConstraintKit is a DSL to make easy & impressive Auto Layout constraints on iOS, tvOS & OSX with Swift Installation Using CocoaPods

A compact but full-featured Auto Layout DSL for Swift
A compact but full-featured Auto Layout DSL for Swift

Mortar allows you to create Auto Layout constraints using concise, simple code statements. Use this: view1.m_right |=| view2.m_left - 12.0 Instead of:

The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. Objective-C and Swift compatible.
The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. Objective-C and Swift compatible.

The ultimate API for iOS & OS X Auto Layout — impressively simple, immensely powerful. PureLayout extends UIView/NSView, NSArray, and NSLayoutConstrai

Comments
  • Consider how to make container

    Consider how to make container "hug" content for any minor alignment

    When a view's minor alignment is SLAlignmentFill then all subviews will fit the container and any of them that have a hugging priority will cause the container to be as small as possible. When any other alignment is specified then the container is free to get as big as it wants along the minor axis.

    It would be nice to set a "hug" priority at which the minor axis will try to get as small as possible. This would allow a set of horizontal views to be top-aligned, but the container will only be as tall as the tallest subview.

    opened by bridger 0
Owner
Bridger Maxwell
Bridger Maxwell
UIStackView replica for iOS 7.x and iOS 8.x

TZStackView A wonderful layout component called the UIStackView was introduced with iOS 9. With this component it is really easy to layout components

Tom van Zummeren 1.2k Oct 10, 2022
A micro UIStackView convenience API inspired by SwiftUI

Stacks A micro UIStackView convenience API inspired by SwiftUI. let stack: UIView = .hStack(alignment: .center, margins: .all(16), [ .vStack(spaci

Alexander Grebenyuk 74 Jul 27, 2022
Porting UIStackView to iOS 7+

OAStackView iOS 9 introduced the very cool UIStackView, UIStackView can be used to easily create simple and complex layouts. As expected UIStackView c

Omar Abdelhafith 2.2k Dec 3, 2022
MZFormSheetPresentationController provides an alternative to the native iOS UIModalPresentationFormSheet, adding support for iPhone and additional opportunities to setup UIPresentationController size and feel form sheet.

MZFormSheetPresentationController MZFormSheetPresentationController provides an alternative to the native iOS UIModalPresentationFormSheet, adding sup

Michał Zaborowski 979 Nov 17, 2022
🎸🎸🎸 Common categories for daily development. Such as UIKit, Foundation, QuartzCore, Accelerate, OpenCV and more.

?????? Common categories for daily development. Such as UIKit, Foundation, QuartzCore, Accelerate, OpenCV and more.

77。 423 Jan 4, 2023
An UITextView in Swift. Support auto growing, placeholder and length limit.

GrowingTextView Requirements iOS 8.0 or above Installation CocoaPods GrowingTextView is available through CocoaPods. To install it, simply add the fol

Kenneth Tsang 941 Jan 5, 2023
Dynamic textview with auto-resizing height & width that is also movable/draggable.

MarkupTextView Dynamic textview with auto-resizing height & width that is also movable/draggable. Requirements iOS 13 or above Installation MarkupText

Seok Kwun Park 2 Nov 17, 2022
A fancy hexagonal layout for displaying data like your Apple Watch

Hexacon is a new way to display content in your app like the Apple Watch SpringBoard Highly inspired by the work of lmmenge. Special thanks to zenly f

Gautier Gédoux 340 Dec 4, 2022
Windless makes it easy to implement invisible layout loading view.

Windless Windless makes it easy to implement invisible layout loading view. Contents Requirements Installation Usage Looks Credits Communication Licen

ArLupin 940 Dec 22, 2022
High performance Swift treemap layout engine for iOS and macOS.

Synopsis YMTreeMap is a high performance treemap layout engine for iOS and macOS, written in Swift. The input to YMTreeMap is a list of arbitrary numb

Yahoo 118 Jan 3, 2023