I just learned anchors for placing views in iOS, and they totally blew my mind. If you’re setting any auto layout constraints programmatically with NSLayoutConstraint’s
constraintWithItem:attribute:relatedBy:toItem:attribute:multiplier:constant:
, you know how ugly and verbose it can be – and you definitely want to check out anchors.
Want to center your segmented control horizontally 20 points from the top of the view? Forget NSLayoutConstraint; use anchors!
let control = UISegmentedControl(items: ["Staging", "Production"])
control.selectedSegmentIndex = 1
control.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(control)
control.topAnchor.constraintEqualToAnchor(view.topAnchor, constant: 20).active = true
control.centerXAnchor.constraintEqualToAnchor(view.centerXAnchor).active = true
Anchors are available in iOS 9.0 and later.