2014-10-04 31 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