自动布局的基本用法

1.最简单用法


  //简单添加控件
    UIButton *button = [[UIButton alloc] init];
    button.backgroundColor = [UIColor redColor];
    //必须说明,以前一下转化就不要用了,就是直接的自动布局.
    button.translatesAutoresizingMaskIntoConstraints = NO;

    [button setTitle:@"自动布局" forState:UIControlStateNormal];
    [button setTitleColor:[UIColor whiteColor]  forState:UIControlStateNormal];
    [button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];

    //如果要用到父类的约束,就要先添加
    [self.view addSubview:button];

    //添加width约束
    // constraintWithItem:自己控件 attribute:约束 relatedBy:等于还是大于 toItem:别人控件 attribute:约束 multiplier:乘以多少 constant:加多少
    //这个约束是,自己宽是300.0
    NSLayoutConstraint *with_Constraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeWidth relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:300.0];
    [button addConstraint:with_Constraint];

    //高度的约束
    NSLayoutConstraint *height_Constraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeHeight relatedBy:NSLayoutRelationEqual toItem:nil attribute:NSLayoutAttributeNotAnAttribute multiplier:0.0 constant:300];
    [button addConstraint:height_Constraint];

    //边距的约束,右边的约束 这个约束和父类有关系,所以就父类加约束
    NSLayoutConstraint *right_Constraint =[NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeRight relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeRight multiplier:1.0 constant:-10];
    [self.view addConstraint:right_Constraint];


    //下面的约束
    NSLayoutConstraint *bottom_Constraint = [NSLayoutConstraint constraintWithItem:button attribute:NSLayoutAttributeBottom relatedBy:NSLayoutRelationEqual toItem:self.view attribute:NSLayoutAttributeBottom multiplier:1.0 constant:-10];
    [self.view addConstraint:bottom_Constraint];



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值