In my View Controller's .xib file I'm using a UITableView
which has a dynamic number of rows. Because it's not the only element in the .xib file (there are other elements below and above it), I need to change it's height constraint after I know the number of rows.
To achieve this, I'm using this solution that works fine.
Therefore:
@implementation MyViewController
{
__weak IBOutlet UITableView *_tableView;
__weak IBOutlet NSLayoutConstraint *_tableViewHeightConstraint;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
[self adjustHeightOfTableview];
}
- (void)adjustHeightOfTableview
{
CGFloat height = _tableView.contentSize.height;
_tableViewHeightConstraint.constant = height;
[self.view needsUpdateConstraints];
}
Now this works fine, but the problem is that you can see the height changing when the ViewController is being shown (because of doing this in viewDidAppear
of course).
I would like to avoid this and when the ViewController is being shown, it should be shown directly with the needed height.
I've tried calling adjustHeightOfTableview
in viewDidLayoutSubviews
instead of viewDidAppear
as suggested here, but that gives me this error:
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after sending -viewDidLayoutSubviews to the view controller. MyViewController's implementation needs to send -layoutSubviews to the view to invoke auto layout.'
I noticed that if I call [self.view layoutSubviews];
at the end of my adjustHeightOfTableview
method, then I don't get any error, but my table view is not visible at all. Checking _tableView.contentSize.height
with the debugger in viewDidAppear
show me that it has the right value. (according to my number of rows)
Calling [self.view layoutIfNeeded];
or [self.view setNeedsLayout];
at the end of my adjustHeightOfTableview
method has the same behavior as calling [self.view layoutSubviews];
: no error, but my table view is not visible.
In case it matters, I'm using a custom UITableViewCell
.
Does anybody know what am I doing wrong?