0

I have the following code to add a UITableView with offset constraints:

self.tableView = UITableView()
self.view.addSubview(self.tableView)

let views: NSDictionary = ["tableView": self.tableView]
let horizontal: NSArray = NSLayoutConstraint.constraintsWithVisualFormat("H:|[tableView]|", options: NSLayoutFormatOptions(0), metrics: nil, views: views)
let vertical: NSArray = NSLayoutConstraint.constraintsWithVisualFormat("V:|[tableView]|", options: NSLayoutFormatOptions(0), metrics: ["offsetTop": 150, "offsetBottom": 49], views: views)

var constraints: NSMutableArray = NSMutableArray()
constraints.addObjectsFromArray(horizontal)
constraints.addObjectsFromArray(vertical)
self.view.addConstraints(constraints)

I keep getting the following error:

(
    "<NSLayoutConstraint:0x17e8d9f0 V:|-(0)-[UITableView:0x18893a00]   (Names: '|':UIView:0x17d7da90 )>",
    "<NSLayoutConstraint:0x17e8da50 V:[UITableView:0x18893a00]-(0)-|   (Names: '|':UIView:0x17d7da90 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x17d886e0 h=--& v=--& V:[UITableView:0x18893a00(0)]>",
    "<NSLayoutConstraint:0x17d88bd0 'UIView-Encapsulated-Layout-Height' V:[UIView:0x17d7da90(568)]>"
)

Will attempt to recover by breaking constraint 
<NSLayoutConstraint:0x17e8da50 V:[UITableView:0x18893a00]-(0)-|   (Names: '|':UIView:0x17d7da90 )>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Is there something i'm doing wrong? I'm trying to basicaly get a UITableView with an offset at top and bottom. I was reading hte following on this page:

https://medium.com/@jsleeuw/mastering-programmatic-auto-layout-b02ed2499d79

KVISH
  • 12,923
  • 17
  • 86
  • 162

1 Answers1

2

If you create views programatically and use auto layout, you need to disable the default constraints UIKit creates first by calling setTranslatesAutoresizingMaskIntoConstraints() before you insert the view into the hierarchy:

self.tableView = UITableView()
self.tableView.setTranslatesAutoresizingMaskIntoConstraints(false)
self.view.addSubview(self.tableView)
jou
  • 5,824
  • 3
  • 22
  • 24