Pedroinpeace
Pedroinpeace

Reputation: 1439

iOS UITableView override autolayout constraints programatically after setTableHeaderView

Okey so this is my dilemma atm.

I have a storyboard with a UITableView (tableView) and UIView (viewForTableHeader) that contains several other objects like a UIImag a label and such.

Programatically I set the UIView to be the header of the UITableView by doing:

    [self.tableView setTableHeaderView:self.viewForTableHeader];

This works perfectly when Not using the autolayout.

But with autolayout the app crashes and leaves me with:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. UITableView's implementation of -layoutSubviews needs to call super.'

So in viewDidLoad I have tried to set the constraints of the viewForTableHeader to be:

NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:self.viewForTableHeader attribute:NSLayoutAttributeTop relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:NSLayoutAttributeTop multiplier:0 constant:0];
[self.view addConstraint:constraint];
constraint = [NSLayoutConstraint constraintWithItem:self.viewForTableHeader attribute:NSLayoutAttributeLeft relatedBy:NSLayoutRelationEqual toItem:self.tableView attribute:NSLayoutAttributeLeft multiplier:0 constant:0];
[self.view addConstraint:constraint];

and I also tried:

- (void)layoutSublayersOfLayer:(CALayer *)layer {
    [super layoutSublayersOfLayer:self.tableView.layer];

and did same thing trying to set the constraints here

}

Is it maby better to have the viewForTableHeader in a nib file? I do am a bit noobish at this so realy any help or pointers would be helpful.

Upvotes: 0

Views: 2357

Answers (1)

Mariam K.
Mariam K.

Reputation: 620

Since you have both (the tableView and the headerView) in IB, you can drag the viewForTableHeader to (over) the tableView and set it as table header.

This will make the headerView appear below the tableView in the views hierarchy.

If you do this you'll be able to remove/add this view to the table later during run time with no auto layout errors or extra constraints.

  [self.viewForTableHeader removeFromSuperview];

and later

  [self.tableView setTableHeaderView:self.viewForTableHeader];

Upvotes: 1

Related Questions