Create a gist now

Instantly share code, notes, and snippets.

Explaining Intrinsic Content Size
//
// How can intrinsic content size help make my layouts cleaner?
// More on http://candycode.io/how-can-intrinsic-content-size-help-make-my-layouts-cleaner/
import UIKit
import XCPlayground
var view = UIView(frame: CGRect(x: 0, y: 0, width: 600, height: 600))
view.backgroundColor = .whiteColor()
XCPlaygroundPage.currentPage.liveView = view
var leftLabel = UILabel()
leftLabel.text = "Lefty"
leftLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(leftLabel)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[left]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["left": leftLabel]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[left]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["left": leftLabel]))
var rightLabel = UILabel()
rightLabel.text = "Righty"
rightLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(rightLabel)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("[left]-[right]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["left": leftLabel, "right": rightLabel]))
view.addConstraint(NSLayoutConstraint(item: leftLabel, attribute: .CenterY, relatedBy: .Equal, toItem: rightLabel, attribute: .CenterY, multiplier: 1.0, constant: 0))
leftLabel.text = "A really long text."
view
var bottomLabel = UILabel()
bottomLabel.text = "Below"
bottomLabel.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(bottomLabel)
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("|-[bottom]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["bottom": bottomLabel]))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[left]-[bottom]", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["left": leftLabel, "bottom": bottomLabel]))
view
leftLabel.text = "HUGE"
leftLabel.font = UIFont.systemFontOfSize(48)
view
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment