Autolayout自动布局1

本文详细介绍了如何在视图中设置控件的宽度、高度以及与边界的距离,通过添加约束来实现精准布局。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需求:控件宽300高100,距离底部10,距离右边10

最终效果如图:


    // 1.创建控件
    UIView *blueView = [[UIView alloc] init];
    [self.view addSubview:blueView];
    blueView.backgroundColor = [UIColor blueColor];
    //不要将AutoresizingMask转为Autolayout的约束
    blueView.translatesAutoresizingMaskIntoConstraints = NO;
    
    // 2.添加约束
    //添加宽度约束:300
    NSLayoutConstraint *widthConstraint = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:300];
    [blueView addConstraint:widthConstraint];
    
    //添加高度约束:100
    NSLayoutConstraint *heightConstraint = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:100];
    [blueView addConstraint:heightConstraint];
    
    //添加右边约束:blueView的右边距离父控件右边有10的间距
    NSLayoutConstraint *rightConstraint = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:blueView.superview attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10];
    [blueView.superview addConstraint:rightConstraint];
    
    //添加底部约束:blueView的底部距离父控件的底部有10的间距
    NSLayoutConstraint *bottomConstraint = [NSLayoutConstraint constraintWithItem:blueView attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:blueView.superview attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10];
    [blueView.superview addConstraint:bottomConstraint];


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值