Auto Layout In Swift Made Easy

Related tags

Layout Swiftstraints
Overview

Swiftstraints

Swiftstraints can turn verbose auto-layout code:

let constraint = NSLayoutConstraint(item: blueView,
                               attribute: NSLayoutAttribute.Width,
                               relatedBy: NSLayoutRelation.Equal,
                                  toItem: redView,
                               attribute: NSLayoutAttribute.Width,
                              multiplier: 1.0,
                                constant: 0.0)

Into one just one line of code:

let constraint = blueView.widthAnchor == redView.widthAnchor

Or transform your less than consise visual format language code:

let constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[leftView]-10-[rightView]|",
                               options: NSLayoutFormatOptions(0),
                               metrics: nil,
                               views: ["leftView":leftView, "rightView":rightView])

Into the following:

let constraints = NSLayoutConstraints("H:|[\(leftView)]-10-[\(rightView)]|")

That was easy!

Installation

Swiftstraints is available through CocoaPods. To install, simply include the following lines in your podfile:

use_frameworks!
pod 'Swiftstraints'

Be sure to import the module at the top of your .swift files:

import Swiftstraints

Alternatively, clone this repo or download it as a zip and include the classes in your project.

Constraints

With Swiftstraints you can create constraints that look just Apple's generic constraint definition:

item1.attribute1 = multiplier × item2.attribute2 + constant

Swifstraints utilizes the new layout anchors introduced in iOS 9:

let view = UIView()
view.widthAnchor
view.heightAnchor
view.trailingAnchor
view.centerXAnchor
etc...

Swiftstraints implements operator overloading so that you can easily create custom constraints:

let blueView = UIView()
let redView = UIView()
let constraint = blueView.heightAnchor == redView.heightAnchor

Just as you would expect, you can specify a multiplier:

let constraint = blueView.heightAnchor == 2.0 * redView.heightAnchor

Or add a constant:

let constraint = blueView.heightAnchor == redView.heightAnchor + 10.0

You can specify inequalities:

let constraint = blueView.heightAnchor <= redView.heightAnchor

And you can define constant constraints if you so choose:

let constraint = blueView.heightAnchor == 100.0

Swiftstraints can readily compute relatively complex constraints:

let constraint = blueView.heightAnchor * 1.4 - 5.0 >= redView.heightAnchor / 3.0 + 400

It's really easy.

Visual Format Language

Apple provides an API that lets you create multiple constraints simultaneously with the Visual Format Language. As we saw before it can be a little cumbersome:

let constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|[leftView]-10-[rightView]|",
                               options: NSLayoutFormatOptions(0),
                               metrics: nil,
                               views: ["leftView":leftView, "rightView":rightView])

Swiftstraints uses string interpolation to let you specify the same constraints in one line of code:

let constraints = NSLayoutConstraints("H:|[\(leftView)]-10-[\(rightView)]|")

Swiftstraints also extends UIView so that you can add constraints easily using the interpolated string format:

superview.addConstraints("H:|[\(leftView)]-10-[\(rightView)]|")

Super easy, super simple.

Revision History

  • 3.0.1 - Bug fixes and limited iOS 8 support (Thank you catjia1011)
  • 3.0.0 - Updated to Swift 3
  • 2.2.0 - Added support for UILayoutPriority
  • 2.1.0 - Fixed a view reference bug and added a new convenience method for adding constraints
  • 2.0.2 - Added support for tvOS target.
  • 2.0.1 - Updated to include support for axis anchors, increased test coverage and more documentation.
  • 2.0.0 - Updated for Swift 2.0 and iOS 9. Now uses layout anchors for simple constraints and string interpolation for Visual Format Language constraints.
  • 1.1.0 - Minor API tweaks
  • 1.0.0 - Initial Release

Author

Brad Hilton, [email protected]

License

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

Comments
  • Fixed init(H: VFLComponent, options: NSLayoutConstraint.FormatOptions = []) and init(V: VFLComponent, options: NSLayoutConstraint.FormatOptions = [])

    Fixed init(H: VFLComponent, options: NSLayoutConstraint.FormatOptions = []) and init(V: VFLComponent, options: NSLayoutConstraint.FormatOptions = [])

    Hello. Thank you for Swiftstraints. In this pull request I fixed the problem with the Array elements type create with init(H: VFLComponent, options: NSLayoutConstraint.FormatOptions = []) and init(V: VFLComponent, options: NSLayoutConstraint.FormatOptions = []). Currently the following test fails:

    func testVFLComponent2() {
        class MyConstraint: NSLayoutConstraint {
                
        }
            
        let superview = UIView()
        let view1 = UIView()
        let view2 = UIView()
        superview.addSubview(view1)
        superview.addSubview(view2)
    
        _ = {
            let shorthandConstraints = [MyConstraint](H:|-[view1]-(>=5)-[view2]-3-|)
            let normalConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-[view1]-(>=5)-[view2]-3-|",
                                                                   options: [],
                                                                   metrics: nil,
                                                                   views: ["view1" : view1, "view2" : view2])
            for (lh, rh) in zip(shorthandConstraints, normalConstraints) {
                XCTAssert(lh == rh)
            }
        }()
    }
    
    opened by RomanPodymov 1
  • Carthage Support & Gitignore Additions

    Carthage Support & Gitignore Additions

    This PR adds a shared scheme for the project, making it compatible with Carthage as a result.

    I've also added Github's suggested Gitignore for Swift projects & removed a couple of project related files that would otherwise have been ignore.

    opened by SimonRice 1
  • New vfl experiment

    New vfl experiment

    New awesome experimental sugar,

    NSLayoutConstraints(H:|-[view1]-(>=5)-[view2]-3-|)
    NSLayoutConstraints(H:|-[view1]-(>=5)-[view2:==view1]-3-|)
    NSLayoutConstraints(H:|-30-[view1:==3.~(.high)]-10-[view2:>=5]-30-|)
    NSLayoutConstraints(V:|[view1:20]-10-[view2]-(30.~(.required-1))-|)
    

    Thanks for inspiration from https://github.com/0xc010d/VFLToolbox

    opened by catjia1011 1
  • Fix an issue that equal numbers will be discarded in metrics hash table

    Fix an issue that equal numbers will be discarded in metrics hash table

    Sorry I made a mistake when changing the hash table's options. Since the “redundant” (for Swift 3.1) init methods are removed, the numbers are fetched and stored in a different way. "Weak" cannot be used, moreover, numbers of equal values should not be treated as the same, either.

    I've added .objectPointerPersonality to solve this crash.

    Case: H:|-(\(number1))-[\(view)]-(\(number2))-|, in which number1 is equal to number2, e.g. both are 15.

    opened by catjia1011 1
  • Missing parameter names

    Missing parameter names

    There are 4 issues with missing parameter names. In file NSLayoutConstraint+Implementation.swift, there are missing an argument labels, "right:", for the function mergeConstraints. There's another missing argument label, "rawValue:", in LayoutConstraints.swift for NSLayoutFormatOptions.

    NSLayoutConstraint+Implementation.swift line #73, 77, 81. LayoutConstraint.swift line #25

    Another option would be to omit the external parameter name in the function definition if you'd like to keep it that way.

    There is also a remnant of Swift 1 in LayoutConstraint.swift on line #44. The enumerate function no loner takes an array as an argument, instead it is now a function of the object itself.

    for (index, object) in enumerate(array) in should be for (index, object) in array.enumerate()

    Look forward to using your pod. It will clean up my project very nicely.

    opened by galenom 1
  • ==!, >=! and <=!

    ==!, >=! and <=!

    Hello. Thank you for Swiftstraints. In this pull request I added 3 new operators ==!, >=! and <=!. They are similar to ==, >= and <=, but the constraints created with ==!, >=! and <=! are activated by default.

    opened by RomanPodymov 0
  • View count fix for cases like `[view1]-[view2(==view1)]` cases

    View count fix for cases like `[view1]-[view2(==view1)]` cases

    NSHashTable.contains uses its own pointer options when comparing. So also added metrics.contains, just to align with views.contains condition.

    This commit fixes the cases when one same view appears for multiple times in one same VFL string, e.g. [view1]-[view2(==view1)]

    opened by catjia1011 0
  • How to use with `addConstraints()`?

    How to use with `addConstraints()`?

    Swiftstraints helps me a lot because it reduces a lot of codes and I love it. One thing I'm curious is, if there's another way of adding constraints instead of set isActive on each constraint.

    As is:

            let iconView = UIImageView(image: UIImage(named: "Icon"))
            view.addSubview(iconView)
            iconView.translatesAutoresizingMaskIntoConstraints = false
            (iconView.widthAnchor == 120.0).isActive = true
            (iconView.heightAnchor == 120.0).isActive = true
            (iconView.centerXAnchor == view.centerXAnchor).isActive = true
            (iconView.centerYAnchor == view.centerYAnchor - Spacing.large).isActive = true
    

    To be:

            let iconView = UIImageView(image: UIImage(named: "Icon"))
            view.addSubview(iconView)
            iconView.translatesAutoresizingMaskIntoConstraints = false
            iconView.addConstraints([
                    (iconView.widthAnchor == 120.0),
                    (iconView.heightAnchor == 120.0),
                    (iconView.centerXAnchor == view.centerXAnchor),
                    (iconView.centerYAnchor == view.centerYAnchor - Spacing.large)
            ])
    

    But the To be code isn't compiled, it says: Error:(17, 41) binary operator '==' cannot be applied to two 'NSLayoutXAxisAnchor' operands.

    Is there any workaround? Thank you.

    opened by YoonjaeYoo 1
Releases(5.2.0)
Owner
null
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
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
Written in pure Swift, QuickLayout offers a simple and easy way to manage Auto Layout in code.

QuickLayout QuickLayout offers an additional way, to easily manage the Auto Layout using only code. You can harness the power of QuickLayout to align

Daniel Huri 243 Oct 28, 2022
Easy Auto Layout

RKAutoLayout Easy AutoLayout TL;DR let view1: UIView = UIView() let view2: UIView = UIView() view1.addSubview(view2) /// Add all view1.rk_alAdd(

Roman Kotov 1 Mar 24, 2019
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

layoutBox 2.1k Dec 22, 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
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
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:

Jason Fieldman 83 Jan 29, 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
Yet Another Swift Auto Layout DSL

FormationLayout Documentation FormationLayout is the top level layout class for one root view. FormationLayout takes a UIView as its rootView. transla

Evan Liu 53 Mar 31, 2022
Lightweight declarative auto-layout framework for Swift

SwiftyLayout SwiftyLayout is a framework that allows to describe layout constraints (ie NSLayoutConstraint) as a simple mathematical formula in a Swif

Hisakuni Fujimoto 15 Nov 7, 2017
Minimal Auto Layout in Swift

Restraint Restraint is a very very small library to help make your use of NSLayoutConstraint in Swift more legible & declarative. Like programmatic vi

The Puffin Supply Project 80 Aug 23, 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
SuperLayout is a Swift library that makes using Auto Layout a breeze.

SuperLayout is a library that adds a few custom operators to Swift that makes using the amazing NSLayoutAnchor API for Auto Layout a breeze. SuperLayo

Lionheart Software 53 Oct 12, 2022
Declarative Auto Layout in Swift, clean and simple

Tails Tails is a take on declarative Auto Layout. If you don't like typing (like me), it might be your kind of thing! Tails is written in Swift and cu

Nick Tymchenko 17 Jan 31, 2019
Fast Swift Views layouting without auto layout. No magic, pure code, full control and blazing fast

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]

layoutBox 2.1k Jan 2, 2023
TinyConstraints is the syntactic sugar that makes Auto Layout sweeter for human use.

TinyConstraints is the syntactic sugar that makes Auto Layout sweeter for human use. Features Pure Swift 5 sweetness. Everything you can do with Auto

Robert-Hein Hooijmans 3.8k Jan 5, 2023
Intuitive and powerful Auto Layout library

Align introduces a better alternative to Auto Layout anchors. Semantic. Align APIs focus on your goals, not the math behind Auto Layout constraints. P

Alexander Grebenyuk 338 Oct 18, 2022