简体   繁体   中英

How to update size constraint of view based on size of superview using Auto Layout?

I want self.boardView , which is a subview of the controller's view, to be sized to the largest square that fits inside its superview. I set constraints in IB so that self.boardView is centered, and I have outlets for the width and height constraints. I am doing the following in the controller:

-(void)updateViewConstraints {
    [super updateViewConstraints];

    const CGFloat W = self.view.bounds.size.width;
    const CGFloat H = self.view.bounds.size.height;
    const CGFloat S = (W < H) ? W : H;

    self.boardViewWidthConstraint.constant = S;
    self.boardViewHeightConstraint.constant = S;
}

The problem is that the controller's view bounds are not necessarily up to date (eg, after a rotation). How/where can I set the constraints above based on the new size of the superview?

This may be a "chicken and egg" problem since the view sizes can't be updated until the new constraints are set, but I can't compute the constraints until the view sizes are updated.

There are apparently changes in iOS8 how updateViewConstraints is called, see Behavior changes for updateViewConstraints in iOS 8 .
I suggest trying

-(void)layoutSubviews {
    [super layoutSubviews];

    const CGFloat W = self.view.bounds.size.width;
    const CGFloat H = self.view.bounds.size.height;
    const CGFloat S = (W < H) ? W : H;

    self.boardViewWidthConstraint.constant = S;
    self.boardViewHeightConstraint.constant = S;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM