一种常见的布局场景就是空页面上竖直方向要展示文案和按钮,同时两者要在屏幕中整体居中,这种情况相信大家在日常开发中肯定都会碰到。相信大部分都是使用一个占位视图,然后用 ImageView
和 Label
把 View
撑开,确定其 size
,然后再让 View
放在 SuperView
的中心,这样也就满足了上面说的需求。在 iOS9 之前也确实只能这样实现。但是在 iOS9 之后,有了另一种新的方式,那就是使用 UILayoutGuide
。
self.button = [UIButton new];
self.button.translatesAutoresizingMaskIntoConstraints = NO;
self.button.backgroundColor = [UIColor cyanColor];
[self.button setTitle:@"确定" forState:UIControlStateNormal];
self.label = [UILabel new];
self.label.translatesAutoresizingMaskIntoConstraints = NO;
self.label.text = @"这是一个测试文案";
self.containerGuide = [UILayoutGuide new];
self.containerGuide.identifier = @"占位区域";
[self.view addSubview:self.button];
[self.view addSubview:self.label];
[self.view addLayoutGuide:self.containerGuide];
[self.containerGuide.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor].active = YES;
[self.containerGuide.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor].active = YES;
[self.button.centerXAnchor constraintEqualToAnchor:self.containerGuide.centerXAnchor].active = YES;
[self.label.topAnchor constraintEqualToAnchor:self.containerGuide.topAnchor].active = YES;
[self.label.leftAnchor constraintEqualToAnchor:self.containerGuide.leftAnchor].active = YES;
[self.label.rightAnchor constraintEqualToAnchor:self.containerGuide.rightAnchor].active = YES;
[self.button.topAnchor constraintEqualToAnchor:self.label.bottomAnchor constant:10].active = YES;
[self.button.centerXAnchor constraintEqualToAnchor:self.containerGuide.centerXAnchor].active = YES;
[self.button.bottomAnchor constraintEqualToAnchor:self.containerGuide.bottomAnchor].active = YES;