我有三个 UIImageView
(水平并排放置),我想在 self.view
内水平和垂直居中,它们之间的水平间距固定他们。我不太了解布局约束的使用,我知道将它们放入中间容器中然后适当设置 autoresizingMask
就可以解决问题:
containerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
如果不使用中间容器,要达到同样的效果需要什么?
最佳答案
假设您的 View 中有 ImageView leftImageView
、rightImageView
和 centerImageView
,这些约束应该可以解决问题:
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:centerImageView
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0]];
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:centerImageView
attribute:NSLayoutAttributeCenterY
relatedBy:NSLayoutRelationEqual
toItem:self.view
attribute:NSLayoutAttributeCenterY
multiplier:1
constant:0]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[leftImage]-[centerImage]-[rightImage]"
options:NSLayoutFormatAlignAllCenterY
metrics:nil
views:@{@"leftImage" : leftImageView,
@"rightImage" : rightImageView,
@"centerImage" : centerImageView}]];
确保 translatesAutoresizingMaskIntoConstraints
在每个 ImageView 上都是 false。
关于ios - 以编程方式设置一组 View 的布局约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22409266/