2014-10-04 34 views
0

我已经做了一个小示范来展示我的应用程序正在发生什么。基本上,我想为左上角的UIView设置动画,占用整个屏幕宽度的一半,占据整个宽度,并在屏幕右上角“推”UIView。然后在稍后的动画中,我想将UIView放回到屏幕上,并将左侧的视图重新调整为其开始的半屏宽度。用Autolayout改变UIView的宽度

我已经采取了一些截图来证明与我现在有它的方式会发生什么。 这是怎么开始的: ​​ 然后调整左视图 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]; 
    } 
} 

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

+0

你可以尝试以下方法:通过constraint.constant =常数设置新的宽度后,插入[containerView layoutIfNeeded]; containerView是你的蓝图的超级视图。 – 2014-10-04 19:45:53

回答

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; 
    } 
} 
+0

这是黄金。谢谢! – Idan 2015-04-27 21:00:25