Skip to content

Instantly share code, notes, and snippets.

@gtranchedone
Last active January 7, 2017 10:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gtranchedone/8597444213731c278f08d10d80dc2200 to your computer and use it in GitHub Desktop.
Save gtranchedone/8597444213731c278f08d10d80dc2200 to your computer and use it in GitHub Desktop.
Auto Layout Example: Manual Layout
// A view containing stacked title and message labels
// The entire layout is manually calculated every time the view has to be rendered or it's requested to re-layout
class SomeView: UIView {
let titleLabel = UILabel(frame: .zero)
let messageLabel = UILabel(frame: .zero)
// ...other subviews
override func layoutSubviews() {
super.layoutSubviews()
let elementsDistance = 20
titleLabel.sizeToFit()
let titleLabelX = (bounds.size.width - titleLabel.bounds.size.width) / 2 // center horizontally
let titleLabelOrigin = CGPoint(x: titleLabelX, y: elementsDistance)
titleLabel.frame = CGRect(origin: titleLabelOrigin, size: titleLabel.bounds.size)
messageLabel.sizeToFit()
let messageLabelX = (bounds.size.width - messageLabel.bounds.size.width) / 2 // center horizontally
let messageLabelOrigin = CGPoint(x: messageLabelX, y: titleLabel.frame.maxY + elementsDistance)
messageLabel.frame = CGRect(origin: messageLabelOrigin, size: massageLabel.bounds.size)
// ...and so on for all other elements
}
// add the subviews to the view hierarchy at some point
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment