VFL子视图居中

简介:

今天做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]];

同理垂直居中也是

相关文章
|
Android开发 数据格式 XML
Android FrameLayout子view居中(左居中,右居中)等
Android的布局FrameLayout默认是把布局内的子view堆砌在左上角,但是,可以通过设置子view的: android:layout_gravity 此参数控制子view的布局位置,实现FrameLayou...
2274 0
|
8月前
|
XML Java Android开发
Android 中ScrollView垂直滚动视图之隐藏滚动条的三种方法
Android 中ScrollView垂直滚动视图之隐藏滚动条的三种方法
90 0
|
10月前
R|绘图边距及布局
R|绘图边距及布局
|
11月前
|
前端开发 JavaScript
【前端】相对定位实现十字居中(上下左右居中)
【前端】相对定位实现十字居中(上下左右居中)
71 0
|
Android开发 容器
ScrollView(滚动条)
本节带来的是Android基本UI控件中的第十个:ScrollView(滚动条),或者我们应该叫他 竖直滚动条,对应的另外一个水平方向上的滚动条:HorizontalScrollView,先来一发官方文档 的链接:ScrollView,我们可以看到类的结构如下
131 0
UITextView设置边框
UITextView设置边框
46 0
超级居中
超级居中
60 0
超级居中
AppBarLayout 折叠之后有阴影?
AppBarLayout 折叠之后有阴影?
102 0
|
Android开发
如何去掉listview滑动时的阴影
如何去掉listview滑动时的阴影
如何去掉listview滑动时的阴影
|
Android开发
Android隐藏Listview和RecyclerView 滑动边界的阴影,去除滚动条加分隔线等
Android隐藏Listview和RecyclerView 滑动边界的阴影,去除滚动条加分隔线等
171 0