TIMEX
TIMEX

Reputation: 271674

If I want to create these constraints programatically, how do I do so?

Storyboard Screenshot

I have a UITableView with those constraints. I'm trying to create the UITableView programmatically, but still want these constraints in code.

Upvotes: 0

Views: 61

Answers (2)

Sahil
Sahil

Reputation: 9226

one way to do is :

let newView = UIView()
newView.backgroundColor = UIColor.redColor()
newView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(newView)


  let horizontalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Leading, multiplier: 1, constant: 0)
 view.addConstraint(horizontalConstraint)

  let verticalConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: -15)
 view.addConstraint(verticalConstraint)

   let widthConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0)
   view.addConstraint(widthConstraint)

   let heightConstraint = NSLayoutConstraint(item: newView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0)
  view.addConstraint(heightConstraint)

for more info you can follow this Swift | Adding constraints programmatically

Upvotes: 0

Eendje
Eendje

Reputation: 8883

You can do this relatively easy by using visual format language:

Add your view, topLayoutGuide and bottomLayoutGuide to a dictionary. I used views. You also have to set translatesAutoresizingMaskIntoConstraints to false for the constraints to work.

Example:

view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|[yourView]-(-15)-|", options: [], metrics: nil, views: views))
view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[topLayout][yourView][botLayout]", options: [], metrics: nil, views: views))

Upvotes: 2

Related Questions