I haven't done much UI Programmatically, but I have a UIView and I want a UILabel to be constrained to the top left corner of the UIView and then have another one but constrained to the top right corner this time. I'm fully aware of how to do this on the GUI but I was wondering how I would go about this purely through swift/programmatically.
This is done with NSLayoutConstraint class.
Firstly, add your label as subview:
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(label)
Here is my extension in order to easily add constraints to subviews. The main method here for you to study is func pin(firstSubview subview1:UIView, firstEdge edge1:NSLayoutAttribute, secondSubview subview2:UIView, secondEdge edge2:NSLayoutAttribute, with constant:Float)
extension UIView {
func pinSubview(_ subview:UIView, toEdge edge:NSLayoutAttribute, withConstant constant:Float) {
self.pinSubviews(self, subview2: subview, toEdge: edge, withConstant: constant)
}
func pinSubviews(_ subview1:UIView, subview2:UIView, toEdge edge:NSLayoutAttribute, withConstant constant:Float) {
pin(firstSubview: subview1, firstEdge: edge, secondSubview: subview2, secondEdge: edge, with: constant)
}
func pin(firstSubview subview1:UIView, firstEdge edge1:NSLayoutAttribute, secondSubview subview2:UIView, secondEdge edge2:NSLayoutAttribute, with constant:Float) {
let constraint = NSLayoutConstraint(item: subview1, attribute: edge1, relatedBy: .equal, toItem: subview2, attribute: edge2, multiplier: 1, constant: CGFloat(constant))
self.addConstraint(constraint)
}
func pinSubview(_ subview:UIView, withHeight height:CGFloat) {
let height = NSLayoutConstraint(item: subview, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: height)
self.addConstraint(height)
}
func pinSubview(_ subview:UIView, withWidth width:CGFloat) {
let width = NSLayoutConstraint(item: subview, attribute: .width, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: width)
self.addConstraint(width)
}
}
Then you have very simple usage:
self.view.pinSubview(label, toEdge: .left, withConstant: 0)
self.view.pinSubview(label, toEdge: .top, withConstant: 0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With