• Stars
    star
    355
  • Rank 119,764 (Top 3 %)
  • Language
    Objective-C
  • Created over 11 years ago
  • Updated almost 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

alternative system for creating and adding Cocoa Auto Layout constraints

Auto Layout Shorthand

Auto Layout Shorthand (ALS) is an alternative system for creating and adding Auto Layout constraints.

It feels kind of like CSS, though more powerful and without HTML's frustrating default layout model.

Here's a simple example to introduce ALS:

[iconView als_addConstraints:@{
 @"left ==": als_superview,
 @"width ==": @(kIconWidth),
 @"top ==": als_superview,
 @"height ==": @(kIconHeight),
 }];

Here's mostly1 the same example using the Visual Format Language (VFL):

[iconView.superview addConstraints:@[
 [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[iconView(kIconWidth)]"
                                         options:0
                                         metrics:NSDictionaryOfVariableBindings(kIconWidth)
                                           views:NSDictionaryOfVariableBindings(iconView)],
 [NSLayoutConstraint constraintsWithVisualFormat:@"V:|[iconView(kIconHeight)]"
                                         options:0
                                         metrics:NSDictionaryOfVariableBindings(kIconHeight)
                                           views:NSDictionaryOfVariableBindings(iconView)],
 ]];

And mostly2 the same example using +[NSLayoutConstraint constraintWithItem:…]:

[iconView.superview addConstraints:@[
 [NSLayoutConstraint constraintWithItem:iconView
							  attribute:NSLayoutAttributeLeft
							  relatedBy:NSLayoutRelationEqual
								 toItem:iconView.superview
							  attribute:NSLayoutAttributeLeft
							 multiplier:1.0
							   constant:0.0],
 [NSLayoutConstraint constraintWithItem:iconView
							  attribute:NSLayoutAttributeWidth
							  relatedBy:NSLayoutRelationEqual
								 toItem:nil
							  attribute:NSLayoutAttributeNotAnAttribute
							 multiplier:1.0
							   constant:kIconWidth],
 [NSLayoutConstraint constraintWithItem:iconView
							  attribute:NSLayoutAttributeTop
							  relatedBy:NSLayoutRelationEqual
								 toItem:iconView.superview
							  attribute:NSLayoutAttributeTop
							 multiplier:1.0
							   constant:0.0],
 [NSLayoutConstraint constraintWithItem:iconView
							  attribute:NSLayoutAttributeHeight
							  relatedBy:NSLayoutRelationEqual
								 toItem:nil
							  attribute:NSLayoutAttributeNotAnAttribute
							 multiplier:1.0
							   constant:kIconHeight],
 ]];

Auto Layout Shorthand Reference

Auto Layout Shorthand is a poor man's DSL wedged into a normal Objective-C dictionary literal.

Each key-value pair contains enough information to create one NSLayoutConstraint. This stands in contrast to VFL, where one string can be used to generate multiple constraints.

The dictionary key encodes two pieces of information: the NSLayoutConstraint's firstAttribute and its relation. Here's some examples:

  • @"width >="
  • @"height <="
  • @"centerX =="

For the first part of the key, the attribute, every NSLayoutAttribute is supported except NSLayoutAttributeNotAnAttribute. See the ALS Dictionary Key Name column below (we'll get to ALS Dictionary Value Name in a moment):

NSLayoutAttribute constant ALS Dictionary Key Name ALS Dictionary Value Name
NSLayoutAttributeLeft left als_left
NSLayoutAttributeRight right als_right
NSLayoutAttributeTop top als_top
NSLayoutAttributeBottom bottom als_bottom
NSLayoutAttributeLeading leading als_leading
NSLayoutAttributeTrailing trailing als_trailing
NSLayoutAttributeWidth width als_width
NSLayoutAttributeHeight height als_height
NSLayoutAttributeCenterX centerX als_centerX
NSLayoutAttributeCenterY centerY als_centerY
NSLayoutAttributeBaseline baseline als_baseline

The second part of the dictionary key encodes the NSLayoutRelation in the obvious manner:

NSLayoutRelation constant Auto Layout Shorthand equivalent
NSLayoutRelationLessThanOrEqual <=
NSLayoutRelationEqual ==
NSLayoutRelationGreaterThanOrEqual >=

The dictionary value encodes either a relation or a constant. Simple relations and simple constants are directly assigned:

  • @"top ==": headerView.als_bottom
  • @"width ==": @(42)

Let's talk about headerView.als_bottom some more. als_bottom is a method added as a category to UIView. Auto Layout Shorthand adds a suite of methods, one for each NSLayoutAttribute. That's the ALS Dictionary Value Name column above.

These categories enable you to refer to both a view and an attribute in one expression. The result is a simple class that just packages up both of them into one object that's later consumed by -[UIView(AutoLayoutShorthand) als_addConstraints:].

You can use a dictionary to specify more complex constraints:

  • @"top ==": @{als_view:headerView.als_bottom, als_constant:@(10)},
  • @"width ==": @{als_constant:@(42), als_priority:@(UILayoutPriorityDefaultHigh)]

Supported keys are:

Auto Layout Shorthand Key Corresponding NSLayoutConstraint property
als_view secondItem
als_multiplier multiplier
als_constant constant
als_priority priority

Finally, VFL has @"|", which represents the superview. als_superview is ALS's version of the same thing.

Auto Layout Shorthand Advantages

  • More concise than +[NSLayoutConstraint constraintWithItem:…] but just as powerful. Actually, just a smidge more powerful since you can specify the constraint's priority at creation time.

  • Easier to read+understand than +[NSLayoutConstraint constraintWithItem:…].

  • Often more concise than even Visual Format Language, yet more powerful (Auto Layout Shorthand can specify centerX and centerY).

  • Refactoring-friendly. Visual Format Language strings are opaque to Xcode's refactoring support. This results in nasty runtime exceptions if you use refactoring to rename a variable or property and forget to update any corresponding VFL string.

  • View Property-friendly. This code doesn't work:

      [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[self.iconView(32)]"
                                              options:0
                                              metrics:nil
                                                views:NSDictionaryOfVariableBindings(self.iconView)];
    

    apparently because of the self.. One work-around is to access the ivar directly:

      [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[_iconView(32)]"
                                              options:0
                                              metrics:nil
                                                views:NSDictionaryOfVariableBindings(_iconView)];
    

    which I don't much care for since it bypasses the accessor. I recommend creating the dictionary yourself:

      [NSLayoutConstraint constraintsWithVisualFormat:@"H:|[iconView(32)]"
      	                                    options:0
                                              metrics:nil
                                                views:@{@"iconView": self.iconView}];
    

    or using ALS.

  • Built-in Closest-Common-Superview Discovery. When relating attributes across views, Auto Layout Shorthand automatically calculates the views' closest common superview and adds the generated constraints there. This is the Apple-recommended place to put your constraints.

Auto Layout Shorthand Disadvantages

  • Another Dependancy. Not that bad though, since it's a self-contained .h/.m pair.

  • Another thing to learn. You probably have to learn VFL anyway to understand Auto Layout's debugging logs.

  • Encourages you to think of constraints being applied to the target view itself instead of the superview they're actually added to. I think removing the level of indirection is worth it.

  • Like Only God Can Create A Tree, Only VFL Can Create NSSpacers. Fortunately ALS plays nicely with VFL, so use VFL if you want to take advantage of spacers.

See Also

TODO

  • Write an example apps to showcase common scenarios.

  • Either upgrade als_superview to a UIView or remove it altogether. Probably the former -- it's not strictly needed (you can always just myview.superview, but the conceptual clarity is worth a more-complicated implementation AFAICS.

Version History

v1.0: Apr 06 2014

v0.4: Jun 24 2013

  • [NEW] Improved handling for groups of constraints (the common case):

    • als_addConstraints: now returns an array of the constraints its created.

    • als_activateConstraints and als_deactivateConstraints category methods on NSArray allow enabling and disabling groups of NSLayoutConstraints.

      Coupled with als_addConstraints: above, this allows you to create groups of constraints, easily switching them on or off based on user interaction and/or application state.

    • als_hostView and als_setHostView: category methods on NSLayoutConstraint handle the to-one nature ((UI|NS)View <->> NSLayoutConstraint) of views and their constraints and to keep track of which host view a constraint has been assigned to so it can be activated (added) and deactivated (removed) easily at runtime.

    • als_isActive and als_setActive: category methods on NSLayoutConstraint to provide individual constraint activation control. Used by als_activateConstraints & als_deactivateConstraints.

This replaces the idea that I'd add a way to get/set constraints by their ALS keys previously mentioned in the TODO section. Also the idea to allow overwriting of previously-set constraints.

v0.3: Jun 18 2013

  • [DEV] Re-unify UIView and NSView implementations.

v0.2: May 22 2013

v0.1.1: Apr 24 2013

  • [FIX] Make Closest-Common-Superview a little more forgiving.

v0.1: Apr 22 2013

  • Initial version.

    As its Semantic Version suggests, its interface may still change in client-breaking ways.


  1. Actually +[NSLayoutConstraint constraintsWithVisualFormat:…] will create a constraint with an attribute of NSLayoutAttributeLeading where the example above uses NSLayoutAttributeLeft. ALS does support @"leading ==" in addition to @"left ==", I just wanted to make the example straightforward to folks who haven't learned about Auto Layout's Right-To-Left text system support yet.

  2. Same deal as 1.

More Repositories

1

mogenerator

Core Data code generation
Objective-C
3,029
star
2

jrswizzle

one-stop-shop for all your method swizzling needs
Objective-C
2,659
star
3

mach_inject

interprocess code injection for Mac OS X
C
810
star
4

clicktoflash

WebKit plug-in to prevent automatic loading of Adobe Flash content
Objective-C
714
star
5

markdownlive

Purpose-built Markdown Editor for Mac OS X with Live Preview
C
496
star
6

mach_override

runtime function overriding for Mac OS X
C
427
star
7

mach_star

code injection and function overriding for Mac OS X
C
254
star
8

JREnum

macros that automate vending an NSString given an enum value (f.x. MyEnumToString(value))
Objective-C
153
star
9

jrfeedbackprovider

nonviral cocoa source for implementing an application feedback panel (for bugs, feature requests and support)
Objective-C
114
star
10

lich

Simple, general, human-sympathetic binary data format
Objective-C
104
star
11

OAuthConsumer

fork of http://code.google.com/p/oauth/ 's Obj-C 2 API
Objective-C
82
star
12

JRTranscriptView

Purpose-built text view for logging output. iOS 7+
Objective-C
67
star
13

stressdrive

tool to completely fill a drive with random data and ensure it can be entirely correctly read back
C
60
star
14

NSInvocation-blocks

Even-easier NSInvocation creation thanks to blocks
Objective-C
54
star
15

JRErr

light at the end of the NSError** tunnel
Objective-C
51
star
16

SafariSessionSaver

Simple app that archives (and restores) Safari's currently-open windows+tabs
Objective-C
50
star
17

MagicHat

Objective-C Binary Documentation Tool. Think classdump with a hyperlinked GUI.
C
43
star
18

bdalias

Simple Cocoa wrapper for Carbon Aliases
Objective-C
38
star
19

Blitz

20 slides. 15 seconds each. 5 minutes total. Go.
Objective-C
32
star
20

JRTruthTable

tell it the current conditions, and it will tell you the current state
Objective-C
31
star
21

node-mysql-oil

slick api on top of node-mysql
JavaScript
30
star
22

clonedrive

paranoid bytewise drive cloning
C
26
star
23

JRLog

Simple but flexible Log4J-like logging system for Objective-C
Objective-C
26
star
24

SafeToUnplug

tiny faceless background app that notfies you when it's actually safe to unplug a drive
Objective-C
22
star
25

ForceQuitUnresponsiveApps

Small background app for Mac OS X 10.6+ that automatically force-quits hung apps
C
22
star
26

BlockStep

makes async code (Obj-C+Blocks) read kinda like sync code
Objective-C
21
star
27

NSKeyedArchiver-butWithNSError

Categories to make NSKeyedArchiver & NSKeyedUnarchiver easier to use and report errors via NSError**
Objective-C
19
star
28

CodaAutosaveOnDeactivate

Coda plugin to automatically save edited documents upon application focus resignation
C
19
star
29

nginx-homebrew-support

support files for nginx-homebrew running as a machine-wide service
Ruby
15
star
30

OpenRadarApp

client-side app for automatically posting Apple-filed RADARs to OpenRadar
JavaScript
14
star
31

webedit

think TextEdit but using WebKit
Objective-C
13
star
32

hypo

why just #import a header file when you can import the object itself?
Objective-C
12
star
33

JRKVOBlocks

Another take on integrating KVO with Blocks. 10.6+manual memory management assumed
Objective-C
12
star
34

ComplimentKit

opt-in to automatically receive flattrs (microdonations) as your users use your mac app
12
star
35

UIView-jr_addConstraints

easier notation for adding Auto Layout constraints to UIView
Objective-C
11
star
36

CoreData-JRExtensions

Objective-C
10
star
37

JRPDFLabel

Design your interface in Interface Builder using custom fonts without having to bundle them
Objective-C
9
star
38

NSXReturnThrowError

Adds origin information to NSError and eases wrapping error codes
Objective-C
9
star
39

Transformation-Matrix-Funhouse

demo of -webkit-transform: matrix3d() (and transformation matrices in general)
JavaScript
9
star
40

JSRegexTeststand

simple single-page app to dynamically develop and test javascript regular expressions
HTML
9
star
41

jryaml

Modern YAML for ObjC. Uses libyaml and Mike Schrag's MDYAML
8
star
42

woplat

WOInstaller + Wonder Web Server Adaptor + OS Support Files
C
8
star
43

unpopular

Chrome Extension that hides indicators of social status on GitHub (watchers, stars, forks) and Twitter (followers, retweets, favs)
CSS
8
star
44

UIView-jr_viewInSuperview

Let's make it easier to create an Auto Layout-ed UIView
Objective-C
7
star
45

MiscMerge

textual templates for Obj-C
Objective-C
6
star
46

BillingsCal

Simple comprehensive live reporting of Billings' database
Objective-C
6
star
47

TwitterReflectorDish

a simple twitter reflector dish (used for @c4)
6
star
48

Function.introspect.js

Small javascript library that interrogates a function to return its name, argument names and source code
JavaScript
6
star
49

ply

minimalist CSS library
5
star
50

xib2pdflabels

tool that generates a multipage PDF, one page per JRPDFLabel view
Objective-C
5
star
51

atomicity

Blast from the Classic Mac OS past. Atomic Locks, Stacks, Guarded Stacks, Queues, and Guarded Queues
C
5
star
52

JRCenteringScrollView

UIScrollView subclass that uses Auto Layout to center its content
Objective-C
5
star
53

slowgold

minimal osx app launcher/switcher
Objective-C
4
star
54

docker-webobjects

WebObjects under Docker. Dead can dance.
4
star
55

catchr

es6 const assignment even with exceptional code
JavaScript
4
star
56

git-import-commit

like git-cherry-pick, but with more sledgehammer
C
4
star
57

CALayer-jr_UIColor

Easily get+set CALayer background and border colors as UIColors in an ARC-safe fashion.
Objective-C
4
star
58

pomodoro

fork of http://github.com/ugol/pomodoro
C
4
star
59

rentzsch.tumblr.com-theme

Tumblr theme used by rentzsch.tumblr.com + MarsEdit
3
star
60

nsxmlelement-elementwithxmlformat

Easier ObjC XML generation
Objective-C
3
star
61

burndeck

SIMBL plugin that adds CD burning to http://www.tapedeckapp.com
Objective-C
3
star
62

simplest-multiplexed-framing-protocol

simple binary protocol for concurrent async unix sockets
C
3
star
63

jsongo

like mongo db, except stores data in git-friendly flat json files
TypeScript
3
star
64

JRLogDemo

Simple app demonstrating JRLog
Objective-C
3
star
65

docker-webobjects-wotaskd

WebObjects' wotaskd in handy container form
3
star
66

qunit

would be a fork of http://github.com/jquery/qunit if that actually held anything
JavaScript
3
star
67

access-date

AppleScript Addition (osax) to retrieve a file's last access date
C
2
star
68

Saw

External-process output destination for JRLog
Objective-C
2
star
69

CoreEndian-RuntimeTarget

Header file with macros for targeting specific endian targets with CoreEndian
C
2
star
70

ReactiveCocoaExample1

Objective-C
2
star
71

dbslayer

unofficial github clone of official dbslayer svn repo
JavaScript
2
star
72

node-arq

node.js implementation of arq backup
2
star
73

jsontable

Simple, efficient, flexible, streamable tabular textual data format
TypeScript
2
star
74

mach_error-Decoder-Ring

simple+lame cocoa app that decodes mach_error integers
Objective-C
2
star
75

Math.uuid.js

fork of Robert Kieffer's Math.uuid.js in jquery.pkg format
JavaScript
2
star
76

elemental

An intrusive, fast (constant-speed), doubly-linked list in C
C
2
star
77

usc

United States Customary Unit lengths (inches, feet) calculator in JS
TypeScript
1
star
78

wiki

wolf's personal wiki
1
star
79

do-dns

command-line tool for downloading and uploading Digital Ocean DNS records
TypeScript
1
star
80

SwiftCoreDataRelationshipRepro

simple Mac app that reproduces failure to set a to-one relationship using Core Data with Swift (Xcode 6b3-4)
Swift
1
star
81

docker-apache-webobjects

Apache + WebObjects Adapter under Docker
1
star
82

giles

simple ajax frontend to DBSlayer
1
star
83

node-google-image-search-url-results

simple node frontend to google image search results (as an array of urls)
JavaScript
1
star
84

WhitelistDeliciousContentSecurityPolicy

Adds https://delicious.com to GitHub's Content-Security-Policy Header so its bookmarklet works
JavaScript
1
star
85

pretty164

Simple E.164 dash-inserter
TypeScript
1
star