Scott Zhu
Scott Zhu

Reputation: 8441

[Auto layout]Attaching UIView to the bottom of its superview while superview's height is changing

I have a superview which is just a subclass of UIView, and I have a subview which is a subclass of UIImageView that I want to attach to the bottom of the superview.

The height of the subview is fixed, but the height of the superview is subject to change. So basically, I want the subview to always attach to the bottom of the superview while I change the height of the superview programatically.

I'm doing it by Auto layout,

enter image description here

So superview has left,top,right attached to its superview, and a fixed height(I gonna change it programatically), here's its constraints,

enter image description here

And the subview has left, bottom, right attached to the superview, and its fixed height, and another constraint that superview's height should equal or greater than the subview's height.

enter image description here

Finally, when I tap the button at the very bottom, I change the height of the superview. Here's the code,

- (IBAction)testButtonPressed:(id)sender {
    [self.dragDownView setFrame:CGRectMake(CGRectGetMinX(self.dragDownView.frame), CGRectGetMinY(self.dragDownView.frame), CGRectGetWidth(self.dragDownView.frame), 100)];
}

However, it's not doing what I wanted, which is keep the subview attached to the bottom of the superview.

Before I change the height:

enter image description here

After I change the height:

enter image description here

As you can see the height of the superview is changed, however the subview still keeps what it was before.

Anyone who can help me?

Upvotes: 0

Views: 687

Answers (2)

Yuvrajsinh
Yuvrajsinh

Reputation: 4584

As you are using Autolayout Constraint you should update Constraint instead of Frame.

Link Height constraint of your Superview to IBOutlet as @mistyhua suggested.

Now when you what to change Height of your Superview then instead of changing frame of Superview change Height Constraint value.

self.heightConstraint.constant = 320;
[self.view layoutIfNeeded];

Upvotes: 0

Mornirch
Mornirch

Reputation: 1144

link constraint: enter image description here

update view's frame like this:

self.heightConstraint.constant = 320;
[self.view layoutIfNeeded];

Upvotes: 1

Related Questions