在使用自动布局dynamic添加子视图的同时调整超级视图的大小

我必须在多个“开关”控件的iPhone屏幕上显示popup窗口。 并且可以分别使用开关打开/closures操作在popup视图上添加和删除子视图。 为了更好地说明情况,请参阅下文

图片。 最初的popover

当用户点击一个button时,上面的popup视图首先出现。 popup必须始终保持在屏幕的中心,最初添加的接触开关将处于closures状态。 打开时,必须在popup窗口中添加以下子视图,同时将popup窗口保持在屏幕的中心位置,并按照子视图增加popup窗口的高度。 添加联系人开关“ON”

就像上面那样,当“添加邮件”开关将会“打开”时,popup视图必须再次增加两个子视图。 最后看起来像这样

最终popoverView

而已。 我通过我的应用程序使用自动布局,这是我困惑的地方。 我知道我可以每次都删除一些新的东西,但这似乎是一种新手select。 那么是否有任何简单的方法来添加子视图,并dynamic扩展其超视图自动布局? 我用UILabel看过很多问题,并且关于它的内在内容大小,但仍然无法理解这个特定的情况。 任何帮助将不胜感激。 快乐的编码。

你可以在视图的出口高度约束,然后相应的设置值为元素。

这可以通过简单的布局约束来实现,而不必手动约束容器视图的高度,然后更新该约束的常量。

做到这一点的方法是根据底部最底层的子视图的底部来限制容器视图的高度。

混合约束

然后在你的视图控制器中引用这个约束。

约束参考

现在你可以写下如下的视图控制器,它将在容器视图的底部添加一个新的子视图,并自动更新容器视图的高度。

#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 

把这一切加在一起,你应该得到以下行为。

在这里输入图像说明