Skip to content

Instantly share code, notes, and snippets.

@nicksnyder
Last active May 9, 2017 21:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nicksnyder/42297f30d0942580ec4046193af11b57 to your computer and use it in GitHub Desktop.
Save nicksnyder/42297f30d0942580ec4046193af11b57 to your computer and use it in GitHub Desktop.
/// A simple hello world view that uses Auto Layout.
public class HelloWorldAutoLayout: UIView {
private lazy var imageView: UIImageView = {
let imageView = UIImageView()
imageView.translatesAutoresizingMaskIntoConstraints = false
imageView.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Vertical)
imageView.setContentHuggingPriority(UILayoutPriorityRequired, forAxis: .Horizontal)
imageView.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Vertical)
imageView.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Horizontal)
imageView.image = UIImage(named: "earth.png")
return imageView
}()
private lazy var label: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = "Hello World!"
return label
}()
public override init(frame: CGRect) {
super.init(frame: frame)
addSubview(imageView)
addSubview(label)
let views = ["imageView": imageView, "label": label]
var constraints = [NSLayoutConstraint]()
constraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("V:|-4-[imageView(==50)]-4-|", options: [], metrics: nil, views: views))
constraints.appendContentsOf(NSLayoutConstraint.constraintsWithVisualFormat("H:|-4-[imageView(==50)]-4-[label]-8-|", options: [], metrics: nil, views: views))
constraints.append(NSLayoutConstraint(item: label, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1, constant: 0))
NSLayoutConstraint.activateConstraints(constraints)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment