A handy tool to constraint UIViews
Constrainter (Constrainer) is a very lightweight constraining tool (inspired by CosmicMind Material layouting syntax) which supports constraining a view to its super and to another view with a very easy syntax. and also you can add your own custom constraint outside the box and keep its reference.
Add this line in your podfile
pod 'Constrainter'
import Constrainter to your class and use follow instructions.
import Constrainter
parentView.addSubview(view)
view.beginConstraints()
.edges()
.endConstraints()
parentView.addSubview(view)
view.beginConstraints()
.center()
.endConstraints()
parentView.addSubview(view)
view.beginConstraints()
.center()
.endConstraints()
view.beginConstraints()
.centerVertically()
.endConstraints()
or
view.beginConstraints()
.centerVertically(-10)
.endConstraints()
or
view.beginConstraints()
.centerVertically(10)
.endConstraints()
view.beginConstraints()
.centerHorizontally()
.endConstraints()
In above samples, Constrainter sets constarint to superview but you can define where to centerHorizontally/centerVertically.
//adding views
let blueButton = UIButton()
let greenButton = UIButton()
parentView.addSubview(blueButton)
parentView.addSubview(greenButton)
//setting greenButton at center of its superview
greenButton.beginConstraints()
.center()
.height(100)
.width(100)
.endConstraints()
and now set blueButton at left side of greenButton:
blueButton.beginConstraints()
.right(10, to: .left, of: greenButton)
.height(100)
.width(100)
.centerVertically()
.endConstraints()
Note: This " to: of: " format can be used with left/right/top/bottom/centerHorizontally/centerVertically operators.
let referencedConst = NSLayoutConstraint()//set what you want and keep its reference for later use.
blueButton.beginConstraints()
.right(10, to: .left, of: greenButton)
.height(100)
.width(100)
.centerVertically()
.customConstraint(referencedConst)
.endConstraints()