ios - 以编程方式设置一组 View 的布局约束

标签 ios objective-c cocoa-touch

我有三个 UIImageView(水平并排放置),我想在 self.view 内水平和垂直居中,它们之间的水平间距固定他们。我不太了解布局约束的使用,我知道将它们放入中间容器中然后适当设置 autoresizingMask 就可以解决问题:

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

如果不使用中间容器,要达到同样的效果需要什么?

最佳答案

假设您的 View 中有 ImageView 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 在每个 ImageView 上都是 false。

关于ios - 以编程方式设置一组 View 的布局约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22409266/

相关文章:

ios - 动态调整 UITableViewCell 到 UILabel 的高度

iphone - 如何标准化 iPhone 应用程序的外观

iphone - UISegmentedControl 值以编程方式更改

iphone - 可与任何 Web 服务 API 交互的 Cocoa 库

iOS如何根据其中的UILabel制作UIView的动态宽度/自动布局

iphone - 如何使用 ALAsset 获取图像的裁剪版本?

ios - ABRecordGetRecordID 返回 -1

iphone - 如何在标签栏应用程序中将 View 旋转为横向

iphone - 填字游戏板的建议

ios - Gtalk 在 iOS 中的实现