以编程方式设置一组视图的布局约束

时间:2014-03-14 15:27:17

标签: ios objective-c cocoa-touch

我有三个UIImageView s(水平放置在彼此旁边),我想在self.view内水平和垂直居中,它们之间有固定的水平间距。我没有很好地掌握使用布局约束,并且知道将它们放入中间容器然后适当地设置autoresizingMask将会起到作用:

containerView.autoresizingMask = UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin;

如果不使用中间容器,可以达到相同的效果吗?

1 个答案:

答案 0 :(得分:1)

假设您的视图中有图片视图leftImageViewrightImageViewcenterImageView,这些约束应该可以解决问题:

[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。

相关问题