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

前端之家收集整理的这篇文章主要介绍了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:@H_403_178@0.0,constant:@H_403_178@200)

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

//高度约束

let height:NSLayoutConstraint =NSLayoutConstraint(item: blueView,attribute: NSLayoutAttribute.Height,constant:@H_403_178@200)

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


//右边约束

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

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


//下边约束

let bottom:NSLayoutConstraint =NSLayoutConstraint(item: blueView,attribute: NSLayoutAttribute.Bottom,attribute:NSLayoutAttribute.Bottom,constant: -@H_403_178@20)

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


效果图:


原文链接:https://www.f2er.com/swift/323916.html

猜你在找的Swift相关文章