Swift开发:NSLayoutConstraint纯代码实现自动布局-初级篇

要求 宽高200的view,通过代码,使得view在距离父控件的右下角20边距处

 

/* 约束的设置,控件内部约束由自己添加,比如宽高,如果是与其他的

           控件约束那么有父控件添加

        

        *创建约束 NSLayoutConstraint  参数 说明:

        * item 自己

        * attribute

        * relatedBy 大于等于 小于等于 等于

        * toItem 另外一个控件

        * attribute 另一个控件的熟悉

        * multiplier 乘以多少

        * constant : 加上多少

        * NSLayoutConstraint : 某个控件的属性值 等于 另外一个控件的属性值 

                       乘以多少 加上多少

        

        * 添加约束 addConstraint

        */



swift 代码:


       let blueView =UIView();

        blueView.backgroundColor =UIColor.blueColor()

        self.view.addSubview(blueView)//系统默认会给autoresizing 约束

// 关闭autoresizing 不关闭否则程序崩溃

        blueView.translatesAutoresizingMaskIntoConstraints =false



       //宽度约束

       let NSLayoutConstraint =NSLayoutConstraint(item: blueView, attribute: NSLayoutAttribute.Width, relatedBy:NSLayoutRelation.Equal, toItem:nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier:0.0, constant:200)

        

        blueView.addConstraint(width)//自己添加约束

        

       //高度约束

       let height:NSLayoutConstraint =NSLayoutConstraint(item: blueView, attribute: NSLayoutAttribute.Height, relatedBy:NSLayoutRelation.Equal, toItem:nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier:0.0, constant:200)

        

        blueView.addConstraint(height)//自己添加约束


       //右边约束

       let right:NSLayoutConstraint =NSLayoutConstraint(item: blueView, attribute: NSLayoutAttribute.Right, relatedBy:NSLayoutRelation.Equal, toItem:self.view, attribute:NSLayoutAttribute.Right, multiplier:1.0, constant: -20)

        

        blueView.superview!.addConstraint(right)//父控件添加约束


       //下边约束

       let bottom:NSLayoutConstraint =NSLayoutConstraint(item: blueView, attribute: NSLayoutAttribute.Bottom, relatedBy:NSLayoutRelation.Equal, toItem:self.view, attribute:NSLayoutAttribute.Bottom, multiplier:1.0, constant: -20)

        

        blueView.superview!.addConstraint(bottom)//父控件添加约束


效果图:


原文地址:https://www.cnblogs.com/Free-Thinker/p/5786878.html