UIView通过自动布局约束动画更改

时间:2014-01-09 07:28:43

标签: ios cocoa-touch uiview autolayout

假设我有一个类似于以下内容的项目:

enter image description here

有两个UIView个 - 一个名为yellowBox,另一个名为redBox。自动布局约束规定yellowBox是超级视图顶部的60个点,具有350个前导和尾随空格(即视图的左侧和右侧)。 redBox具有相同的前导和尾随空间约束。两个0之间有一个垂直空间约束,表示yellowBox的底部应始终直接位于redBox之上。

当用户点击展开黄色框按钮时,我希望yellowBox的高度增加,结果redBox向下移动以继续满足垂直空间约束( yellowBox始终位于redBox之上。这是动画代码:

- (IBAction)expandYellowBox:(id)sender {

    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect newFrame = self.yellowBox.frame;
                         newFrame.size.height += 50;
                         self.yellowBox.frame = newFrame;
                     }];

}

但是,我无法正常工作。正如您在红色图标中看到的那样,目前的约束存在问题:

enter image description here

这是公平的,因为自动布局无法知道盒子的高度。但是,我不知道如何以这样的方式解决这个问题,它将允许调整框的大小和移动。例如,如果我在yellowBox上指定高度约束,那么将阻止其调整大小。如果我将高度约束设置为大于或等于(以允许yellowBox高度增加),那么我得到一个不同的约束错误:

enter image description here

所有约束都是在故事板中使用Xcode建立的 - 没有一个是用代码编写的。

非常感谢任何帮助。


编辑:事实证明,点击按钮时yellowBox正在增长 - 这只是我无法分辨,因为它出现在redBox后面。我只是在四次点击后才注意到它开始出现在redBox的底部。但是,同样的问题仍然存在 - 如何让redBox始终坚持yellowBox的底部。

3 个答案:

答案 0 :(得分:82)

shwet-solanki所述尝试,但在更改约束后添加以下行:

[self.view layoutIfNeeded];
IBAction看起来像是:

- (IBAction)expandYellowBox:(id)sender {

[UIView animateWithDuration:0.5
                 animations:^{
                     self.yellowBoxHeightConstraint.constant += 50;
                     [self.view layoutIfNeeded];
                 }];
}

其中yellowBoxHeightConstraintIBOutlet的高度约束yellowBox。 希望这可以帮助。

答案 1 :(得分:4)

  1. 向两个视图添加高度约束
  2. 为黄色框
  3. 创建高度约束的IBOutlet
  4. 现在不是更改按钮按下事件中黄色框的高度,而是更改高度约束的值。即假设您的IBOutlet约束名称为yellowBoxHeightConstraint,然后yellowBoxHeightConstraint.constant += 50;
  5. 希望这适合你。

答案 2 :(得分:1)

//
//  WPViewController.h
//  AutoLayoutTEst
//
//  Created by VASANTH K on 09/01/14.
//  
//

#import <UIKit/UIKit.h>

@interface WPViewController : UIViewController
@property (strong, nonatomic) IBOutlet UIButton *button1;
- (IBAction)buttClicked:(id)sender;
@property (strong, nonatomic) IBOutlet NSLayoutConstraint *heightConstrain;

@property (strong, nonatomic) IBOutlet UIButton *button2;
@end

点击活动

- (IBAction)buttClicked:(id)sender {


    self.heightConstrain.constant=100;


}

此处您需要为黄色按钮设置heightConstrain,然后为该按钮创建参考插座,然后更新heightConstrain以更新该按钮的大小,它将自动将您的红色按钮向下移动。< / p>

https://github.com/vasanth3008/AutoLayoutHeighDemo

参考我的示例演示项目

相关问题