Change height constraint of table view outside of viewDidAppear in iOS 7

痞子三分冷 提交于 2019-12-11 07:17:37

问题


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 viewDidAppearof 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?


回答1:


Move the code from viewDidAppear: to viewWillAppear:. They are much the same, and valid for much the same sorts of thing, but viewWillAppear: happens out of the user's gaze, which is exactly what you're after. (You'll probably need to call reloadData on the table explicitly first, in order to give it some data.)



来源:https://stackoverflow.com/questions/23464303/change-height-constraint-of-table-view-outside-of-viewdidappear-in-ios-7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!