I want to 'pin' a tableview to it's container, the view of a view controller. Since UIView does not have anchor properties, I try to do it with the layoutMarginsGuide.
UIView does not provide anchor properties for the layout margin attributes. Instead, the layoutMarginsGuide property provides a UILayoutGuide object that represents these margins. Use the guide’s anchor properties to create your constraints.
let margins = self.view.layoutMarginsGuide
self.tableView.leadingAnchor.constraintEqualToAnchor(margins.leadingAnchor).active = true
self.tableView.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor).active = true
But running this code I get the following error:
** Terminating app due to uncaught exception 'NSGenericException', reason: 'Unable to activate constraint with items <UITableView: 0x7fdfd0ab5e00; frame = (0 0; 768 1024); clipsToBounds = YES; gestureRecognizers = <NSArray: 0x7fdfd8452e00>; layer = <CALayer: 0x7fdfd84c11c0>; contentOffset: {0, 0}; contentSize: {0, 0}> and <UILayoutGuide: 0x7fdfd86d7ca0 - "UIViewLayoutMarginsGuide", layoutFrame = {{0, 0}, {0, 0}}, owningView = <UIView: 0x7fdfd75a8aa0; frame = (0 0; 768 1024); autoresize = W+H; layer = <CALayer: 0x7fdfd0409270>>> because they have no common ancestor. Does the constraint reference items in different view hierarchies? That's illegal.'
The important part:
...because they have no common ancestor. Does the constraint reference items in different view hierarchies? That's illegal.'
But how is this supposed to work?
first change constraint to be like this
self.tableView.leftAnchor.constraintEqualToAnchor(view.leftAnchor).active = true
self.tableView.rightAnchor.constraintEqualToAnchor(view.rightAnchor).active = true
if the problem still exist ensure that tableview is added as a subview of view
view.addSubview(tableView)