我正在尝试使用 NSLayoutConstraint 将图片定位到 View 中心,如下所示:
NSInteger userPictureRadius = 50.0F;
UIImageView *imgv = [[UIImageView alloc] initWithFrame:CGRectMake(self.view.bounds.size.width / 2 - userPictureRadius,
self.topArea.bounds.size.height / 2 - userPictureRadius + 20,
userPictureRadius * 2,
userPictureRadius * 2)];
NSString *urlString= [NSString stringWithFormat:@"%@%@",[[Parameters sharedInstance] BASE_URL], [[MyCredentialStore sharedInstance] getPicturePath]] ;
[imgv sd_setImageWithURL:[NSURL URLWithString:urlString] placeholderImage:nil];
imgv.layer.cornerRadius = imgv.frame.size.height / 2;
imgv.layer.masksToBounds = YES;
imgv.layer.borderWidth = 0;
[imgv.layer setBorderColor: [[UIColor blackColor] CGColor]];
[imgv.layer setBorderWidth: 2.0];
[imgv setTranslatesAutoresizingMaskIntoConstraints:NO];
...
[self.topArea addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[imgv(100)]-|"
options:0
metrics:nil
views:elementsDictionary]];
[self.topArea addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[imgv(100)]-|"
options:0
metrics:nil
views:elementsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[_topArea]-|"
options:0
metrics:nil
views:elementsDictionary]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-[_topArea]-[_tableView]-|"
options:0
metrics:nil
views:elementsDictionary]];
这里有两个问题:
图像出现在屏幕的左上角。
顶部区域和屏幕边框之间有一个空白区域。
你能告诉我我的代码有什么问题吗?
最佳答案
这样的居中不能使用自动布局视觉格式语言 (VFL) 来完成。您提供的 VFL 字符串通过标准距离将 ImageView 的边缘与其 super View 相关联。例如,H:|-[imgv(100)]-|
建立了三个约束: ImageView 的前沿等于其父 View 的前沿加上标准距离, ImageView 的宽度为 100 点,并且 super View 的后缘等于 ImageView 的后缘加上标准距离。这将导致指定 ImageView 及其父 View 的大小。我猜 ImageView 将在它的父 View 中居中,但它的父 View 可能不是你期望的大小。
要使一个 View 在另一个 View 中水平居中,请使用类似的东西:
NSLayoutConstraint* constraint = [NSLayoutConstraint constraintWithItem:imgv
attribute:NSLayoutAttributeCenterX
relatedBy:NSLayoutRelationEqual
toItem:imgv.superview
attribute:NSLayoutAttributeCenterX
multiplier:1
constant:0];
[imgv.superview addConstraint:constraint];
你会为垂直方向做类似的事情。如果你想强制 ImageView 为特定大小,你可以为此使用单独的约束。 (如果你愿意,你可以使用 VFL。它类似于 H:[imgv(100)]
。请注意,这里与另一个 View 没有关系,只有宽度。)
关于ios - 以编程方式使用自动布局将图像定位到 View 的中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28032218/