我有两个图像 - profileImageView,profileImageViewOfLoggedInUser,彼此相距20px,我想将它们置于视图中心。
以下是我的源代码
static CGFloat const MeetingDetailNameLabelMarginX = 20;
NSDictionary *views = @{
@"imageView": self.profileImageView,
@"imageViewForLoggedInUser": self.profileImageViewOfLoggedInUser,
@"nameLabel": self.nameLabel,
@"companyNameLabel": self.companyNameLabel,
@"positionLabel": self.positionLabel,
@"statusLabel": self.statusLabel,
};
NSDictionary *metrics = @{
@"imagePaddingLeft": @(MeetingDetailImageViewMarginX),
@"imagePaddingTop": @(MeetingDetailImageViewMarginY),
@"nameLabelPaddingLeft": @(MeetingDetailNameLabelMarginX),
@"nameLabelPaddingRight": @(MeetingDetailNameLabelMarginRightX),
@"nameLabelPaddingTop": @(MeetingDetailImageViewSize + MeetingDetailImageViewMarginY),
@"imageSize": @(MeetingDetailImageViewSize),
@"nameLabelHeight": @(nameLabelFrame.size.height),
@"otherLabelHeight": @(MeetingDetailOtherLabelHeight),
@"dateLabelWidth": @(self.dateLabel.frame.size.width),
@"statusLabelWidth": @(statusFrame.size.width),
@"statusLabelMarginLeftFromView": @(MeetingDetailImageViewMarginX),
};
// image left and width
[self.detailContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[imageView(imageSize)]"
options:0
metrics:metrics
views:views]];
[self.detailContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:[imageView]-imagePaddingLeft-[imageViewForLoggedInUser(imageSize)]"
options:0
metrics:metrics
views:views]];
// image top and height
[self.detailContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-imagePaddingTop-[imageView(imageSize)]"
options:0
metrics:metrics
views:views]];
[self.detailContainer addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-imagePaddingTop-[imageViewForLoggedInUser(imageSize)]"
options:0
metrics:metrics
views:views]];
请告诉我要添加的代码。
我在下面的屏幕截图中看到了添加以下代码的UI: -
NSLayoutConstraint *centerXConstraint = [self.detailContainer.centerXAnchor constraintEqualToAnchor:_profileImageView.centerXAnchor];
[self.detailContainer addConstraint:centerXConstraint];
答案 0 :(得分:1)
如果你想让ImageView相对于它的超级视图,你不应该指定一些奇怪的边距或其他东西。您所要做的就是为居中指定2个约束,为imageView指定2个约束。
从iOS 9开始,您可以使用这些简单的API:
NSLayoutConstraint *centerXConstraint = [superView.centerXAnchor constraintEqualToAnchor:imageView.centerXAnchor];
NSLayoutConstraint *centerYConstraint = [superView.centerYAnchor constraintEqualToAnchor:imageView.centerYAnchor];
NSLayoutConstraint *imageViewHeight = [imageView.heightAnchor constraintEqualToConstant:heightValue];
NSLayoutConstraint *imageViewWidth = [imageView.widthAnchor constraintEqualToConstant:widthValue];
然后,您可以相对于第一个图像视图约束第二个图像视图(因为第一个图像视图已被约束)。您可以使用 VFL 或其他任何内容。