Autolayout自动布局1

来源:互联网 发布:网络赌钱软件 编辑:程序博客网 时间:2024/06/05 19:07

需求:控件宽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];


0 0
原创粉丝点击