[英]Adding a background imageview programmatically with autolayout
我需要为我使用故事板 + 自动布局完成的项目的视图添加背景图像视图。 我想使用代码以编程方式添加此图像。 所以基本上它应该是从顶部 layoutguide 到底部 layoutguide,而不是在它们下面。 我试过几种方法都失败了。
在添加这样的之前,我首先调整 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];
但由于某种原因,我的图像视图仍然在状态栏下。
这就是我添加 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}]];
添加相关topLayoutGuide到约束self.view
是没用的。 视图控制器布局其根视图( 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];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.