我需要为我使用情节提要+自动布局完成的项目的视图添加背景图像视图。我想使用代码以编程方式添加此图像。因此,基本上应该是从顶部布局指南到底部布局指南,而不要深入其中。我尝试了几种失败的方法。
[这样添加之前我首先调整VC'c视图的一种方法
id topGuide = self.topLayoutGuide;
UIView *superView = self.view;
NSDictionary *viewsDictionary = NSDictionaryOfVariableBindings (superView, topGuide);
[self.view addConstraints:
[NSLayoutConstraint constraintsWithVisualFormat:@"V:[topGuide]-20-[superView]"
options:0
metrics:nil
views:viewsDictionary]
];
[self.view layoutSubviews];
但是由于某些原因,我的图像视图仍位于状态栏下。
这是我添加背景图片的方式
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Default"]];
self.backgroundView.contentMode = UIViewContentModeTop;
[self.view insertSubview:self.backgroundView atIndex:0];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[backgroundImageView]|" options:0 metrics:nil views:@{@"backgroundImageView":self.backgroundView}]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[backgroundImageView]|" options:0 metrics:nil views:@{@"backgroundImageView":self.backgroundView}]];
将与topLayoutGuide有关的约束添加到self.view
是没有用的。视图控制器独立于AutoLayout来布局其根视图(self.view
),并将覆盖约束效果(对此,请不要引用我,这是对布局系统的真正了解以外的观察结果)。
相反,将第一个约束(@"V:[topGuide]-20-[superView]"
)添加到self.backgroundView
:
self.backgroundView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Default"]];
self.backgroundView.contentMode = UIViewContentModeTop;
[self.view insertSubview:self.backgroundView atIndex:0];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[topGuide]-(20)-[backgroundImageView]|" options:0 metrics:nil views:@{@"backgroundImageView":self.backgroundView, @"topGuide": self.topLayoutGuide}]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|[backgroundImageView]|" options:0 metrics:nil views:@{@"backgroundImageView":self.backgroundView}]];
[self.view layoutSubviews];