Aliaksandr B.
Aliaksandr B.

Reputation: 146

AutoLayout issue with resizing subviews

I'm trying to figure out how to use Autolayout and I've founded a problem. I want to create a view in IB with size 200x200. This view, called them PieView, has two UIImageViews with frames (0, 0, 200, 200), for both of them. My question is, how to override updateConstraints in code (I like visual format language), or in IB, that if I change size of my PieView (for example to 100), and subviews will changed too (0, 0, 100, 100).

And how can I change the size of PieView, I'm trying for width and for height

NSLayoutConstraint *width = [NSLayoutConstraint constraintWithItem:self
                                                         attribute:NSLayoutAttributeWidth
                                                         relatedBy:NSLayoutRelationEqual
                                                            toItem:nil
                                                         attribute:NSLayoutAttributeNotAnAttribute
                                                        multiplier:1.0f
                                                          constant:100.f];//kDiameter * sizeCoef];

Upvotes: 0

Views: 1095

Answers (2)

bilobatum
bilobatum

Reputation: 8918

I'm not sure that you even need to re-configure the height or width constraints for the image views. If you want the image views to grow and shrink with their superview, then just pin the the sides of the images views to the superview in IB. You would not need to override updateConstraints.

Upvotes: 0

smileyborg
smileyborg

Reputation: 30469

If the subviews of the container view (PieView) are correctly positioned/sized/pinned relative to their container, all you need to do is update the width of the container view (PieView).

To change the view's size in code, you'll need to make sure you keep a reference (in a property, for example) to the constraint on the view's width. So if you added that constraint in Xcode, that means connecting an outlet for that constraint. Or if you added it in code (as you have written in your question), just assign the constraint to a property instead of a local variable.

Then, in updateConstraints, change the constant property of the constraint to the new width. Here's an example:

- (void)updateConstraints
{
    // Probably want to wrap the below line with a check for when you should actually do this change, 
    // as updateConstraints may get called more than once (including when you aren't ready to change the width).
    self.widthConstraint.constant = 100.0f;
}

Then just call setNeedsUpdateConstraints on the view when you're ready to change its width!

Upvotes: 0

Related Questions