Get Updates By E-mail 

Article Written By:
Johann Dowa

Open Source Swift Library That Greatly Simplifies Working With Auto Layout

  •  
  •  
  •  
  •  
  •  

Some time ago I mentioned the objective-c library Masonry that dramatically simplifies programming AutoLayout making your code more concise and readable.

Here’s an open source library called Snap which provides a Swift based implementation of the objective-c Masonry library.

Snap provides its own DSL dramatically reducing the amount of code required to use the Auto Layout API.

This simple example from the readme shows how much code is required to use NSLayoutConstraints to have a view fill its superview inset 10 pixels on each side:

let superview = self;

let view1 = UIView()
view1.setTranslatesAutoresizingMaskIntoConstraints(false)
view1.backgroundColor = UIColor.greenColor()
superview.addSubview(view1)

let padding = UIEdgeInsetsMake(10, 10, 10, 10)

superview.addConstraints([
  NSLayoutConstraint(
    item: view1,
    attribute: NSLayoutAttribute.Top,
    relatedBy: NSLayoutRelation.Equal,
    toItem: superview,
    attribute: NSLayoutAttribute.Top,
    multiplier: 1.0,
    constant: padding.top
  ),
  NSLayoutConstraint(
    item: view1,
    attribute: NSLayoutAttribute.Left,
    relatedBy: NSLayoutRelation.Equal,
    toItem: superview,
    attribute: NSLayoutAttribute.Left,
    multiplier: 1.0,
    constant: padding.left
  ),
  NSLayoutConstraint(
    item: view1,
    attribute: NSLayoutAttribute.Bottom,
    relatedBy: NSLayoutRelation.Equal,
    toItem: superview,
    attribute: NSLayoutAttribute.Bottom,
    multiplier: 1.0,
    constant: -padding.bottom
  ),
  NSLayoutConstraint(
    item: view1,
    attribute: NSLayoutAttribute.Right,
    relatedBy: NSLayoutRelation.Equal,
    toItem: superview,
    attribute: NSLayoutAttribute.Right,
    multiplier: 1.0,
    constant: -padding.right
  )
])

And using Snap this could be as short as:

let padding = UIEdgeInsetsMake(10, 10, 10, 10)

view1.snp_makeConstraints { make in
  make.edges.equalTo(superview).with.insets(padding)
  return // this return is a fix for implicit returns in Swift and is only required for single line constraints
}

You can find Snap on Github here.

A nice Swift based library for working with Auto Layout.


  •  
  •  
  •  
  •  
  •  

Submit A Resource

Have you created a useful tutorial, library or tool for iOS development that you would like to get in front of our 300,000+ monthly page views from iOS developers?

You can submit the url here.

The resources we feel will appeal to our readers the most will be posted on the front page.

Comments