Auto Layout programmatically :
- translatesAutoresizingMaskIntoConstraints :
- For programmatically created view default value is true and views from interface builder is false.
- If this property set too True, the system automatically creates a set of constraints based on view’s frame and its autoresizing mask.
- If you add your own constraint on top of this, they inevitably Conflict with the autogenerated constraints.
- Error : [LayoutConstraints] Unable to simultaneously satisfy constraints. (Error will get for conflict)
- This creates an unsatisfiable layout. So When programmatically instantiating views.
- Be sure to set their translatesAutoresizingMaskIntoConstraints property to NO.
- Layout Anchors :
Auto Layout constraints : * Constraints are set off rule to make os know where to place UI Components. introduced in iOS6 and iPadOS6. * There are two ways to set constraint UI Builder and programmatically.
- First Step: let view = UIView(frame: .zero) view.translatesAutoresizingMaskIntoConstraints = false
- Second Step: There are two ways to set constraint programmatically i.e Anchors or Visual Format Language (or VFL).
- Eg :
- Anchors Language. view.heightAnchor.constraint(equalToConstant:100) view.widthAnchor.constraint(equalToConstant:100)
- VFL let viewDictionary = [“view”: view] let horizontalConstraint = NSLayoutConstraint.constraints(withVisualFormat: “H: [view(100)]”, metrics: nil, views: viewDictionary) let verticalConstraint = NSLayoutConstaint.constaints(withVisualFormat:”V: [view(100)]”,metrics:nil, views:viewDictionary)
Layouts :
locationButton.leadingAnchor.constraint(equalToSystemSpacingAfter: view.leadingAnchor, multiplier: 1)
- The way to read this line of code is this:
- “I would like the location button’s leading anchor to be equal to the system spacing (8 pts) after the view’s leading anchor”. 2 . Apple uses a standard margin spacing of 8 pts. Previously we had been setting it manually. But by using this API we don’t have to. We just have to set its multiplier instead.
- 1 = 8 pts.
- 2 = 16 pts
- 3 = 24 pts and so on.
- This is is functionally equivalent to:
- locationButton.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 8)
- if Apple were ever to change the value of their standard spacing, we would adjust automatically.
view.trailingAnchor.constraint(equalToSystemSpacingAfter: searchButton.trailingAnchor, multiplier: 1)
- We would like the views trailing anchor to be equal to the system spacing after the search button with a multiplier of
- This is is functionally equivalent to:
- searchButton.rightAnchor.constraint(equalTo: view.rightAnchor,constant: -8),
Final Result Design: