我需要为我使用storyboards + autolayout完成的项目添加背景图像视图。我想使用代码以编程方式添加此图像。所以基本上它应该是从顶部布局指南到底部布局指南,而不是在它们之下。我尝试了几种失败的方法。
我首先在添加此类
之前调整VC&#c; 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];
但是对于某些原因,我的imageview仍然在状态栏下。
这就是我添加bg imageview的方式
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}]];
答案 0 :(得分:1)
将与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];