使用自动布局动态添加子视图时调整超级视图
我必须在多个“切换”控件的iPhone屏幕上显示弹出窗口。并分别使用开关打开/关闭动作在弹出视图上添加和删除子视图。为了更好地说明情况,请参阅下面的使用自动布局动态添加子视图时调整超级视图
图像。
当用户点击按钮时,上面的弹出视图首先出现。弹出窗口必须始终保持在屏幕的中心,最初添加的触点开关将处于关闭状态。打开时,必须将下面的子视图添加到弹出窗口中,同时将弹出窗口保留在屏幕中央,并按照子视图增加弹出窗口的高度。
就像上面那样,当“添加邮件”开关将会“打开”时,弹出窗口视图必须再次增加两个子视图的高度。最后这个样子,
就是这样。我通过我的应用程序使用自动布局,这是我困惑的地方。我知道我可以每次删除这些馅饼和一个新的,但这似乎是一种新手选择。那么是否有任何简单的方法来添加子视图并使用自动布局动态扩展它的超级视图?我看到很多UILabel的问题,并且关于它的内在内容大小,但仍然无法理解这种特殊情况。任何帮助将不胜感激。快乐的编码。
您可以对视图的出口高度进行约束,然后将相应的值设置为元素。
您的意思是我必须为所有子视图以及容器弹出窗口视图采用高度约束IBOutlets,并动态更改它们,首先将子视图的约束条件保留为“零”,这不是必需的,然后在需要显示时更改它们并用一些小的扩展动画改变容器视图高度约束? – 2014-12-05 14:01:19
是的。 你不需要3个子视图,你只能用一个子视图来完成。隐藏文本框,然后操作textField.hidden = NO并设置_heightCOnstraint = 60.00; – mokiSRB 2014-12-05 14:55:46
好的。得到它了。谢谢。 – 2014-12-06 05:21:53
这可以用普通布局约束来实现,而不必手动约束容器视图的高度,然后更新该约束的常量。
做到这一点的方法是根据底部最底层的子视图的底部约束容器视图的高度。
然后把一个参照此约束您的视图控制器内。
现在你可以写类似下面的视图控制器,这将在容器视图的底部添加一个新的子视图,并自动更新容器视图的高度。
#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