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 width: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)//父控件添加约束

效果图:

Snip20160708_9.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容