假设我有一个类似于以下内容的项目:
有两个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;
}];
}
但是,我无法正常工作。正如您在红色图标中看到的那样,目前的约束存在问题:
这是公平的,因为自动布局无法知道盒子的高度。但是,我不知道如何以这样的方式解决这个问题,它将允许调整框的大小和移动。例如,如果我在yellowBox
上指定高度约束,那么将阻止其调整大小。如果我将高度约束设置为大于或等于(以允许yellowBox
高度增加),那么我得到一个不同的约束错误:
所有约束都是在故事板中使用Xcode建立的 - 没有一个是用代码编写的。
非常感谢任何帮助。
编辑:事实证明,点击按钮时yellowBox
正在增长 - 这只是我无法分辨,因为它出现在redBox
后面。我只是在四次点击后才注意到它开始出现在redBox
的底部。但是,同样的问题仍然存在 - 如何让redBox
始终坚持yellowBox
的底部。
答案 0 :(得分:82)
按shwet-solanki所述尝试,但在更改约束后添加以下行:
[self.view layoutIfNeeded];
IBAction看起来像是:
- (IBAction)expandYellowBox:(id)sender {
[UIView animateWithDuration:0.5
animations:^{
self.yellowBoxHeightConstraint.constant += 50;
[self.view layoutIfNeeded];
}];
}
其中yellowBoxHeightConstraint
是IBOutlet
的高度约束yellowBox
。
希望这可以帮助。
答案 1 :(得分:4)
yellowBoxHeightConstraint.constant += 50;
希望这适合你。
答案 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
参考我的示例演示项目