SwiftLayoutConstraints
aims to provide expressive NSLayoutConstraint
with Swift.
SwiftLayoutConstraints targets Swift 2.2
and iOS 8
Basic Constraints can be made such as:
// assume we have 2 views and they are added to one parent (view)
let view1 = UIView()
view1.translatesAutoresizingMaskIntoConstraints = false
view1.backgroundColor = UIColor.greenColor()
let view2 = UIView()
view2.translatesAutoresizingMaskIntoConstraints = false
view2.backgroundColor = UIColor.blueColor()
view.addSubview(view1)
view.addSubview(view2)
// Expressions below create, **activate** and return constraints
view1.ls_top | .Left | .Right | view2.ls_left | .Right | .Bottom ~== view
view2.ls_top ~== view1.ls_bottom + 40
view1.ls_height ~== view.ls_height * 0.25 + 50
The above code generates this output:
LayoutConstraints are represented as LayoutConstraintType, and has two implementations:
- LhsLayoutConstraint represents left-hand side, and does NOT support mutating its
constant
andmultiplier.
- RhsLayoutConstraint represents right-hand side, and supports mutating its
constant
andmultiplier.
SwiftLayoutConstraints
introduces operators to represent each NSLayoutRelation
, simply ~
is added before the expressive form of the relation.
~==
forNSLayoutRelation.Equal
~>=
forNSLayoutRelation.GreaterThanOrEqual
~<=
forNSLayoutRelation.LessThanOrEqual
Representing any Relation Operator as :op
, the following expressions are supported:
LhsLayoutConstraint :op LayoutConstraintType
LhsLayoutConstraint :op CGFloat
[LhsLayoutConstraint] :op AnyObject
AnyObject :op [LayoutConstraintType]
[LhsLayoutConstraint] :op [LayoutConstraintType]
- At any point, Left-hand side of any expression is always
LhsLayoutConstraint
- You may create an array of constraints using
|
operator, i.e:view.ls_height | view.ls_width
- Operator
|
also acceptsNSLayoutAttribute
where values (object, constant and multiplier) are taken from previous constraint, i.e:view.ls_top | .Bottom
- You may use
+
or*
to set constraint'sconstant
andmultiplier
, i.e:view1.ls_top ~== view2.ls_bottom * 1 + 20
- Consider operators
precedence
in your expressions, i.e:view.ls_top * 0.5 + 50
is not same asview.ls_top + 50 * 0.5
github "ahmadbaraka/SwiftLayoutConstraints" ~> 1.0
pod 'SwiftLayoutConstraints', '~> 1.0'
SwiftLayoutConstraints is available under the MIT license. See the LICENSE file for more info.