Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save gtranchedone/3154317d2ca73808bab0e22e958add8f to your computer and use it in GitHub Desktop.
Save gtranchedone/3154317d2ca73808bab0e22e958add8f to your computer and use it in GitHub Desktop.
Auto Layout Example: Springs and Structs
// A view containing stacked title and message labels
// The labels have flexible width that changes accordingly to this view's size changes
class SomeView: UIView {
let titleLabel: UILabel
let messageLabel: UILabel
// ...other subviews
override init(frame: CGRect) {
let elementsDistance = 20
let titleLabelSize = CGSize(width: frame.size.width - elementsDistance * 2, height: 21) // 21 because it looks good (seriously)
let titleLabelX = (frame.size.width - titleLabelSize.width) / 2 // center horizontally
let titleLabelOrigin = CGPoint(x: titleLabelX, y: elementsDistance)
let titleLabelFrmae = CGRect(origin: titleLabelOrigin, size: titleLabelSize)
titleLabel = UILabel(frame: titleLabelFrame)
titleLabel.autoresizingMask = .flexibleWidth
let messageLabelSize = CGSize(width: frame.size.width - elementsDistance * 2, height: 21) // 21 because it looks good (seriously)
let messageLabelX = (frame.size.width - messageLabelSize.width) / 2 // center horizontally
let messageLabelOrigin = CGPoint(x: titleLabelX, y: titleLabel.frame.maxY + elementsDistance)
let messageLabelFrmae = CGRect(origin: messageLabelOrigin, size: messageLabelSize)
messageLabel = UILabel(frame: messageLabelFrame)
messageLabel.autoresizingMask = .flexibleWidth
// ...and so on for all other elements
super.init(frame: frame)
addSubview(titleLabel)
addSubview(messageLabel)
// ...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment