我想要的是添加一个图像作为 subview ,然后将其沿 X 轴居中对齐,并距父 View 底部 10 个点。我只需要使用自动布局,最好使用视觉格式化语言。
- (void)viewDidLoad
{
[super viewDidLoad];
self.imageView = [[UIImageView alloc] initWithFrame:CGRectZero];
[self.imageView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.imageView setImage:[UIImage imageNamed:@"06-arrow-south"]];
self.imageView.contentMode = UIViewContentModeScaleAspectFit;
[self.view addSubview:self.imageView];
[self addConstraints];
self.imageView.layer.borderColor = [[UIColor redColor] CGColor];
self.imageView.layer.borderWidth = 1.0;
}
- (void)addConstraints {
NSDictionary *viewsDictionary = @{@"arrowImage":self.imageView};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[arrowImage(==40)]-|"
options:0
metrics:nil
views:viewsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[arrowImage(==40)]-10-|"
options:0
metrics:nil
views:viewsDictionary]];
}
这是我得到的:
最佳答案
V:|-[arrowImage]-10-|
这会对齐 ImageView ,使其距离其父 View 的顶部为标准长度 (20pt),距离底部为 10。您想要的是仅将其固定在底部:
V:[arrowImage]-10-|
我不确定是否可以使用视觉格式在 super View 中居中,但是您可以创建一个约束来居中它:
[self.view addConstraint:
[NSLayoutConstraint
constraintWithItem:self.imageView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0]];
无需设置 ImageView 的高度或宽度;它的大小将由它的内容决定。
因此,这是您的 addConstraints
方法的完整代码:
- (void)addConstraints {
[self.view addConstraint:
[NSLayoutConstraint
constraintWithItem:self.imageView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0]];
NSDictionary *viewsDictionary = @{@"arrowImage":self.imageView};
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:[arrowImage]-10-|"
options:0
metrics:nil
views:viewsDictionary]];
}
关于ios - 将 UIImageView 与自动布局对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21487768/