我有三个UIImageView
s(水平放置在彼此旁边),我想在self.view
内水平和垂直居中,它们之间有固定的水平间距。我没有很好地掌握使用布局约束,并且知道将它们放入中间容器然后适当地设置autoresizingMask
将会起到作用:
containerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;
如果不使用中间容器,可以达到相同的效果吗?
答案 0 :(得分:1)
假设您的视图中有图片视图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
为false。