這可以用普通佈局約束來實現,而不必手動約束容器視圖的高度,然後更新該約束的常量。
做到這一點的方法是根據底部最底層的子視圖的底部約束容器視圖的高度。
然後把一個參照此約束您的視圖控制器內。
現在你可以寫類似下面的視圖控制器,這將在容器視圖的底部添加一個新的子視圖,並自動更新容器視圖的高度。
#import "ViewController.h"
@interface ViewController()
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *bottomConstraint;
@property (weak, nonatomic) IBOutlet UIButton *addButton;
@property (weak, nonatomic) IBOutlet UIView *containerView;
@property (nonatomic, weak) UIView *lastView;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.lastView = self.addButton;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)addButtonTapped:(id)sender {
UIView *newView = [[UIView alloc] initWithFrame:CGRectZero];
newView.translatesAutoresizingMaskIntoConstraints = NO;
newView.backgroundColor = [UIColor redColor];
[newView addConstraint:[NSLayoutConstraint constraintWithItem:newView
attribute:NSLayoutAttributeHeight
relatedBy:NSLayoutRelationEqual
toItem:nil
attribute:NSLayoutAttributeNotAnAttribute
multiplier:1.0
constant:35]];
[self.containerView addSubview:newView];
[self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[lastView]-(14)-[newView]"
options:NSLayoutFormatAlignAllCenterX
metrics:nil
views:@{@"lastView" : self.lastView, @"newView" : newView}]];
[self.containerView addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-(10)-[newView]-(10)-|"
options:NSLayoutFormatAlignmentMask
metrics:nil
views:@{@"newView":newView}]];
[self.containerView removeConstraint:self.bottomConstraint];
self.bottomConstraint = [NSLayoutConstraint constraintWithItem:self.containerView
attribute:NSLayoutAttributeBottom
relatedBy:NSLayoutRelationEqual
toItem:newView
attribute:NSLayoutAttributeBottom
multiplier:1.0
constant:14];
[self.containerView addConstraint:self.bottomConstraint];
self.lastView = newView;
}
@end
加上這一切,你應該得到以下行爲。
在原始情況下,您的約束條件如何? – 2014-12-05 13:44:41
目前我還沒有設置任何約束條件,因爲我無法清楚地知道如何做到這一點,因爲您看到我必須動態添加子視圖,所以我不知道如何使用自動佈局來實現。正如它所說,即使我隱藏了子視圖,那麼它也會在計算子視圖時發揮約束作用。 – 2014-12-05 13:58:32
請在下面查看我的答案,瞭解如何使用佈局約束來實現您的目標。 – 2014-12-06 18:04:32