Concise Auto Layout API to chain programmatic constraints while easily updating existing constraints.

Overview

SnapLayout

Build Status CocoaPods Coverage Status Version Carthage compatible Platform License

Concise API for Auto Layout. SnapLayout extends UIView and NSView to deliver a list of APIs to improve readability while also shortening constraint code. Internally uses AutoLayout to provide the best experience. With SnapLayout, developers can remove boilerplate code but not at the cost of readability.

Imagine applying any or all of the following constraints in one line of code to a view: top, leading, trailing, bottom, width, height, centerX, centerY. Not enough? Start chaining your snap calls to support adjacents snaps. This is all possible with SnapLayout.

Why Use It?

Lets use a real world example. Lets say the following view needs to be added. It has a centerX, centerY, width, and height constraint.

SnapLayout

Apple:

squareView.translatesAutoresizingMaskIntoConstraints = false
squareView.widthAnchor.constraint(equalToConstant: 50)
squareView.heightAnchor.constraint(equalToConstant: 50)
squareView.centerXAnchor.constraint(equalTo: squareSuperview.centerXAnchor, constant: 0)
squareView.centerYAnchor.constraint(equalTo: squareSuperview.centerYAnchor, constant: 0)

SnapLayout:

squareView.snap(width: 50, height: 50, centerX: 0, centerY: 0)

SnapLayout handles translatesAutoresizingMaskIntoConstraints and references the superview of squareView when applying constraints. Built to be flexible, yet readable.

Setup

Requirements

  • Xcode
    • Language Support: Swift (5.0)
    • Fully Compatible With: Xcode 10.0 and higher
  • iOS
    • Fully Compatible With: iOS 9.0 and above
  • macOS
    • Fully Compatible With: macOS 10.11 and above
  • tvOS
    • Fully Compatible With: tvOS 9.0 and above

Installation with CocoaPods

pod "SnapLayout"

Installation with Carthage

github "sp71/SnapLayout"

Usage

Overview

  • All methods are prefixed with snap for quick Xcode autocomplete.
  • Directly uses NSLayoutAnchor under the hood so the API is developer friendly
  • Any view using SnapLayout will not only have its translatesAutoresizingMaskIntoConstraints set to false, but also have its constraint activated.
  • Snap offers many default parameters including the view argument. If a view parameter is not supplied, it is assumed your view will be snapping to its superview.
  • Powerful API supporting snapping of adjacent views

Methods

func snap(to view: View? = nil, top: CGFloat? = nil, leading: CGFloat? = nil, bottom: CGFloat? = nil, trailing: CGFloat? = nil, width: CGFloat? = nil, height: CGFloat? = nil, centerX: CGFloat? = nil, centerY: CGFloat? = nil, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager
func snap(to view: View? = nil, config: SnapConfig, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager
func snapWidth(to view: View, multiplier: CGFloat = 1, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager
func snapHeight(to view: View, multiplier: CGFloat = 1, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager
func snap(size: CGSize, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager
func snap(trailingView: View, constant: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager
func snap(leadingView: View, constant: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager
func snap(bottomView: View, constant: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager
func snap(topView: View, constant: CGFloat = 0, priority: LayoutPriority = LayoutPriorityRequired, isActive: Bool = true) -> SnapManager

Sample Code

let buttonSnapManager = button.snap(top: 50, leading: 50, trailing: 50, width: 30)
buttonSnapManager.top?.constant = 100

Not only has this button applied 4 constraints to its superview, but each individual constraint is accessible through the returned SnapManager type. The beauty of SnapLayout is not only its powerful API interface, but how easy it is to adjust constraints. Other API's simply return an array, but not SnapLayout. Each constraint is neatly packaged into a SnapManager.

Snapping Adjacent Views

button1.snap(trailingView: button2, constant: 8)

These buttons are now side by side where button2 is now the trailingView. No longer will developers have to think which trailing constraint should apply to which leading constraint. This keeps the code lean and clean.

Chaining

let snapManager = view.snap(top: 8, leading: 8, width: 50)
                      .snapHeight(to: superview, multiplier: 0.5)
print(snapManager.top?.constant)    # 8.0
print(snapManager.height?.constant) # 0.5

Snap calls may also be chained and will continue to return a SnapManager.

Config

A SnapConfig struct is also available where a developer may list all of their constraint constants beforehand and provide this type to the snap method argument.

let config = SnapConfig(top: 50, leading: 50, trailing: 50, width: 30, centerX: 0)
button.snap(config: config)

Priority

SnapLayout assumes required priority (same default as Apple) unless otherwise specified for those created constraints.

button1.snap(trailingView: button2, constant: 8, priority: .low)

In the following example, the top, leading, bottom, and trailing constraint all have a priority of required; however, the height constraint has a UILayoutPriority.defaultHigh priority. That's it!

rectangleView.snap(top: 48, leading: 16, bottom: 16, trailing: 16)
             .snap(height: 40, priority: .defaultHigh)

To Activate or not to Activate

SnapLayout, by default, activates all constraints it creates; however, this can be disabled by passing false to isActive.

button1.snap(trailingView: button2, constant: 8, isActive: false)

Debugging

SnapLayout will also print out errors to log if a snap was not properly applied.

SnapLayout Error - No constraint was applied for view: <UIView: 0x7fcb8f4031d0; frame = (0 0; 0 0); layer = <CALayer: 0x608000036320>>

Safe Area Layout Guide Support

SnapLayout will apply constraints using safeAreaLayoutGuide if the app is running iOS 11; otherwise, it will apply the view's layout anchors directly.

Example Apps

To run the example project, run pod try SnapLayout.

This example project contains not only an Example-iOS target, but also an Example-MacOS target. This is a great introduction to become more familiar with the library.

Blogs

Author

Satinder Singh, [email protected]

License

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

Comments
  • Feature/priority

    Feature/priority

    • SnapLayout now supports priority with all snaps!
    • Added test for priority
    • Updated Example project priority cell with update
    • Improved Naming Convention within API from constant to config
    opened by sp71 3
  • Provide Support for activate / inactivate constraints

    Provide Support for activate / inactivate constraints

    Observation Currently, SnapLayout automatically activates constraints before returning to the caller. In some cases, this behavior can be undesirable.

    Enhancement Allow SnapLayout to take in a parameter to activate or deactivate the constraints before returning to the caller. This parameter can have a default value of activate. Also, allow SnapManager to have this behavior as well through a function.

    enhancement 
    opened by sp71 0
  • [FEATURE] Updated SnapLayout to remove negative usage

    [FEATURE] Updated SnapLayout to remove negative usage

    • Previously, bottom and trailing would cause views to overlap when using positive constant values
    • Updated to take in positive inputs to gain distance between views
    • Now negative inputs will mimic the same behavior as other snap methods
      • views will overlap if negative input
      • viwes will gain distance if positive input
    • Update snapSize(size: ...) signature to snap(size: ...) to be more consistent with naming pattern
    opened by sp71 0
  • [FEATURE] Test Coverage For Snap Manager Chaining

    [FEATURE] Test Coverage For Snap Manager Chaining

    • Improved Overall Test Coverage
    • Removed Boilerplate Test Setup into Base class
    • Found bug where SnapManager would not sync with subsequent SnapManager
      • Bug crushed thanks to Unit Tests :)
    opened by sp71 0
  • Fix Builds And Improve Code Coverage

    Fix Builds And Improve Code Coverage

    • Fixed build sometimes failing through workaround
      • Current Open Issue: https://github.com/travis-ci/travis-ci/issues/6675
    • Added .slather.yml for code coverage
    opened by sp71 0
  • [FEATURE] Update SnapLayout with ConstraintManager

    [FEATURE] Update SnapLayout with ConstraintManager

    • Update return values with ConstraintManager & remove [NSLayoutConstraint] returns
    • Remove offset pins and update with ConstraintEdgeInsets for greater consistency
    opened by sp71 0
  • Missing relationships such as constraint top to center

    Missing relationships such as constraint top to center

    I currently don't see a way to create constraints from one view's bottom to another view's center for example.

    For me that's been a use case in views where I want to align a label's bottom to the Y-center of the superview for example. If that label is auto-resizable due to dynamic content, I can't necessarily snap center to center there if the label's bottom should remain fixed.

    Wondering if it's possible to add these kinds of relationships to the feature set.

    enhancement 
    opened by DannyVancura 2
Releases(1.7.0)
Owner
Satinder Singh
Satinder Singh
Swifty DSL for programmatic Auto Layout in iOS

WWLayout Easy to write auto layout constraints, with minimal extensions to standard namespaces. Feature Highlights Easy to use, readable API Backwards

WW Tech 49 Oct 2, 2022
Swift microframework for declaring Auto Layout constraints functionally

Relayout Relayout is a Swift microframework to make using Auto Layout easier with static and dynamic layouts. Why? If you want to build a UI using App

Steve Streza 560 Nov 19, 2022
A powerful Swift programmatic UI layout framework.

Build dynamic and beautiful user interfaces like a boss, with Swift. Neon is built around how user interfaces are naturally and intuitively designed.

Mike 4.6k Dec 26, 2022
Programmatic view layout for the rest of us.

Façade Important Facade is no longer under active development, and as such if you create any issues or submit pull requests, it's not very likely to b

Mike 696 Aug 3, 2022
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

Javier Zhang 74 Oct 19, 2022
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

Malith Nadeeshan 1 Jan 16, 2022
A Swift utility to make updating table views/collection views trivially easy and reliable.

ArrayDiff An efficient Swift utility to compute the difference between two arrays. Get the removedIndexes and insertedIndexes and pass them directly a

Adlai Holler 100 Jun 5, 2022
UIView category which makes it easy to create layout constraints in code

FLKAutoLayout FLKAutoLayout is a collection of categories on UIView which makes it easy to setup layout constraints in code. FLKAutoLayout creates sim

Florian Kugler 1.5k Nov 24, 2022
In this repository I've learned how to use the layout as well as alignment and constraints.

Auto Layout Our Goal At the moment, our app only looks good on the canvas dimension that we’ve selected. If you run the app on screens with different

Pedro Couventaris Daspett 1 Apr 23, 2022
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

PureLayout 7.6k Jan 6, 2023
A custom layout built on top of SwiftUI's Layout API that lays elements out in multiple lines. Similar to flex-wrap in CSS, CollectionViewFlowLayout.

WrapLayout A custom layout built on top of SwiftUI's Layout API that lays elements out in multiple lines. Similar to flex-wrap in CSS, CollectionViewF

Hiroshi Kimura 6 Sep 27, 2022
FlexLayout adds a nice Swift interface to the highly optimized facebook/yoga flexbox implementation. Concise, intuitive & chainable syntax.

FlexLayout adds a nice Swift interface to the highly optimized Yoga flexbox implementation. Concise, intuitive & chainable syntax. Flexbox is an incre

layoutBox 1.7k Dec 30, 2022
Write concise Autolayout code

Winner of Hacking with Swift Recommended award You + Stevia = ?? ?? Write concise, readable layouts ?? Reduce your maintenance time ?? Compose your st

Fresh 3.3k Jan 6, 2023
MisterFusion is Swift DSL for AutoLayout. It is the extremely clear, but concise syntax, in addition, can be used in both Swift and Objective-C. Support Safe Area and Size Class.

MisterFusion MisterFusion makes more easier to use AutoLayout in Swift & Objective-C code. Features Simple And Concise Syntax Use in Swift and Objecti

Taiki Suzuki 316 Nov 17, 2022
ResponderChainDemo - Learned how to use responder chain for communication between the views

ResponderChainDemo Learned how to use responder chain for communication between

Prashant Gaikwad 1 Sep 30, 2022
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

Robb Böhnke 7.3k Jan 4, 2023
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

Carlos Vidal 1.9k Dec 23, 2022
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

null 349 Dec 20, 2022
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

Keshav Vishwkarma 90 Sep 1, 2022