Autolayout自动布局2

本文介绍如何使用Auto Layout在iOS应用中使一个UIView控件实现水平居中、垂直居中,并将其宽度和高度设置为父视图的一半。通过具体的代码示例展示了如何创建约束。

需求:控件水平居中,垂直居中,宽度高度均为父控件的一半



    // 1.创建控件
    UIView *blueView = [[UIView alloc] init];
    [self.view addSubview:blueView];
    blueView.backgroundColor = [UIColor blueColor];
    //不要将AutoresizingMask转为Autolayout的约束
    blueView.translatesAutoresizingMaskIntoConstraints = NO;
    
    // 2.添加约束
    //宽度约束:父控件的一半
    NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:blueView.superview attribute:NSLayoutAttributeWidth multiplier:0.5 constant:0];
    [blueView.superview addConstraint:widthConstraint];
    
    //高度约束:父控件的一半
    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:blueView.superview attribute:NSLayoutAttributeHeight multiplier:0.5 constant:0];
    [blueView.superview addConstraint:heightConstraint];
    
    //水平居中
    NSLayoutConstraint *centerXConstraint = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeCenterX relatedBy:NSLayoutRelationEqual toItem:blueView.superview attribute:NSLayoutAttributeCenterX multiplier:1.0 constant:0];
    [blueView.superview addConstraint:centerXConstraint];
    
    //垂直居中
    NSLayoutConstraint *centerYConstraint = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeCenterY relatedBy:NSLayoutRelationEqual toItem:blueView.superview attribute:NSLayoutAttributeCenterY multiplier:1.0 constant:0];
    [blueView.superview addConstraint:centerYConstraint];


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值