使用Autolayout更改UIView的宽度

时间:2014-10-04 18:38:51

标签: ios autolayout uiviewanimation nslayoutconstraint

我做了一个小型演示来展示我的应用中发生了什么。基本上,我想在左上角设置一个UIView,它占据屏幕宽度的一半,占据整个宽度,并推动"屏幕右上角的UIView。然后在稍后的动画中,我想将UIView带回屏幕,并将左侧视图的大小调整为它开始的半屏宽度。

我已经拍了几张截图来说明我现在拥有它的方式会发生什么。 这就是它的开始: This is how it starts out on launch 然后调整左视图的大小 This is after enlarging the left UIView 试图把它带回来之后 This is after trying to bring it back to half size 这是改变视图大小的代码

- (void)replaceWidthConstraintOnView:(UIView *)view withConstant:(float)constant {

    [self.view.constraints enumerateObjectsUsingBlock:^(NSLayoutConstraint *constraint, NSUInteger idx, BOOL *stop) {
        if ((constraint.firstItem == view) && (constraint.firstAttribute == NSLayoutAttributeWidth)) {
            constraint.constant = constant;
        }
    }];
}

- (IBAction)changeViewSize {


    CGFloat blueViewWidth = self.blueView.bounds.size.width;

    if (blueViewWidth == self.view.bounds.size.width) {

        blueViewWidth = blueViewWidth / 2;
        [self replaceWidthConstraintOnView:self.blueView withConstant:blueViewWidth];

    }
    else {
        blueViewWidth = blueViewWidth * 2;
        [self replaceWidthConstraintOnView:self.blueView withConstant:blueViewWidth];
    }
}

我想知道为什么蓝色视图不会仅仅覆盖屏幕的一半。我感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

我不确定为什么它不能像你写的那样工作,但你可以使用一些相对约束而不是浮点大小。

首先,确保在蓝色视图中将translatesAutoresizingMaskIntoConstraints属性设置为NO。

类似的东西会使蓝色视图的大小是主视图的一半:

[self.view addConstraint:[NSLayoutConstraint
                    constraintWithItem:self.blueView
                    attribute:NSLayoutAttributeWidth
                    relatedBy:NSLayoutRelationEqual
                    toItem:self.view
                    attribute:NSLayoutAttributeWidth
                    multiplier:0.5f
                    constant: 0.0]];

要填充整个视图,您可以遍历所有约束并根据需要修改乘数/常数。例如,这将通过将NSLayoutAttributeWidth约束的乘数设置为1.0来使蓝色视图填充其父级:

for(NSLayoutConstraint *constraint in self.view.constraints)
{
    if(constraint.firstAttribute == NSLayoutAttributeWidth && constraint.secondAttribute == NSLayoutAttributeWidth &&
        constraint.firstItem == self.blueView && constraint.secondItem == self.blueView)
    {
        constraint.multiplier = 1.0;
    }
}
相关问题