这可以用普通布局约束来实现,而不必手动约束容器视图的高度,然后更新该约束的常量。
做到这一点的方法是根据底部最底层的子视图的底部约束容器视图的高度。
然后把一个参照此约束您的视图控制器内。
现在你可以写类似下面的视图控制器,这将在容器视图的底部添加一个新的子视图,并自动更新容器视图的高度。
#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