Signo Signo - 4 months ago 31
Objective-C Question

UIView frame not updating in viewDidAppear

I'm using

Storyboard
with
autolayout
. In my
ViewController
I have a basic structure: one
UIScrollView
and one contentView (
UIView
) that contains different labels). Then I have different elements that I add in the
viewDidAppear
method of the class inside my
contentView
, then in order to recalculate it's frame size I do this:

- (void)fixContentViewHeight {
_contentView.frame = CGRectMake(_contentView.frame.origin.x, _contentView.frame.origin.y, _contentView.frame.size.width, operators.frame.origin.y + operators.frame.size.height);
//constraint for contentView height
_contentViewHeight.constant = operators.frame.origin.y + operators.frame.size.height;

}
- (void)fixScrollViewHeight {
_scrollView.frame = _contentView.frame;
_scrollView.contentSize = _contentView.frame.size;
}


where
operators
is the LAST placed element of
contentView
, it's always on the bottom of the frame. I call these 2 methods inside the
viewDidAppear
and they make the view scrollable, the problem is that the frame of
contentView
doesn't get updated so the last elements are always unclickable (because they're placed outside the frame of the view).

What am I doing wrong? Why the scrollView becomes scrollable but the contentView keeps it's old frame?

Answer

If you have autolayout constraints affecting the height of _contentView You will not be able to change its height by setting the frame, as the constraints will override that.

You will need to (and should be) adding new / modifying constraints in your code when you are adding new elements. then calling

_contentView.layoutIfNeeded()

After all the updates to let the UI update if it needs to, which it should.

Comments