今天做UI用VFL适配在View上添加一个图片想让指定宽高的图片居中显示,我用下面的代码想着能实现可是出来的效果并没有居中。
UIImageView *headView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MR WU.png"]];
[headView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:headView];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-90-[headView(100)]-|" options:0 metrics:nil views:NSDictionaryOfVariableBindings(headView)]];
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"H:|-[headView(100)]-|" options:NSLayoutFormatAlignAllCenterX metrics:nil views:NSDictionaryOfVariableBindings(headView)]];
后来在网上查了下终于找到解决方法
self.view.backgroundColor=[UIColor whiteColor];
UIImageView *headView=[[UIImageView alloc]initWithImage:[UIImage imageNamed:@"MR WU.png"]];
[headView setTranslatesAutoresizingMaskIntoConstraints:NO];
[self.view addSubview:headView];
NSDictionary* views = NSDictionaryOfVariableBindings(headView);
//设置高度
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|-90-[headView(100)]" options:0 metrics:nil views:views]];
//设置宽度
[self.view addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"[headView(100)]" options:0 metrics:nil views:views]];
//水平居中
[self.view addConstraint:[NSLayoutConstraint constraintWithItem:headView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeCenterX multiplier:1 constant:0]];
同理垂直居中也是