I have a UITableView with those constraints. I'm trying to create the UITableView programmatically, but still want these constraints in code.
            Asked
            
        
        
            Active
            
        
            Viewed 58 times
        
    0
            
            
        - 
                    See section on `NSLayoutConstraints` here --> https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/ProgrammaticallyCreatingConstraints.html#//apple_ref/doc/uid/TP40010853-CH16-SW1 – Adrian Jan 23 '16 at 03:27
2 Answers
2
            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))
 
    
    
        Eendje
        
- 8,815
- 1
- 29
- 31
0
            
            
        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

 
     
    