NSLayoutConstraint 是一个很好的解决iphone和ipad适配问题,下面通过实例来简单的介绍一下:
self.view.translatesAutoresizingMaskIntoConstraints = false;
let leftView = UILabel();
leftView.backgroundColor = UIColor.redColor();
leftView.translatesAutoresizingMaskIntoConstraints = false;
self.view.addSubview(leftView);
leftView.text = "layout contraint";
let leftConstraint = NSLayoutConstraint(item: leftView, attribute: .Top, relatedBy: .Equal, toItem: self.view, attribute: .Top, multiplier: 1, constant: 40);
let updaConstraint = NSLayoutConstraint(item: leftView, attribute: .Leading, relatedBy: .Equal, toItem: self.view, attribute: .Leading, multiplier: 1, constant: 40);
let widthL = NSLayoutConstraint(item: leftView, attribute: .Width, relatedBy: .Equal, toItem: self.view, attribute: .Width, multiplier: 0.2, constant: -20);
let heithL = NSLayoutConstraint(item: leftView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier:1, constant: 100);
self.view.addConstraints([heithL,widthL,updaConstraint,leftConstraint]);
let buttom = UILabel();
buttom.text = "button";
buttom.backgroundColor = UIColor.greenColor();
buttom.translatesAutoresizingMaskIntoConstraints = false;
self.view.addSubview(buttom);
let blfetb = NSLayoutConstraint(item: buttom, attribute: .Leading, relatedBy: .Equal, toItem: leftView, attribute: .Trailing, multiplier: 1, constant: 0);
let upbele = NSLayoutConstraint(item: buttom, attribute: .Top, relatedBy: .Equal, toItem: leftView, attribute: .Bottom, multiplier: 1, constant: 0);
let downbel = NSLayoutConstraint(item: buttom, attribute: .Width, relatedBy: .Equal, toItem: leftView, attribute: .Width, multiplier: 1, constant: 0);
let heigjs = NSLayoutConstraint(item: buttom, attribute: .Height, relatedBy: .Equal, toItem: leftView, attribute: .Height, multiplier: 1, constant: 20);
self.view.addConstraints([heigjs,downbel,upbele,blfetb]);
1.如果使用 NSLayoutConstraint 必须设置 translatesAutoresizingMaskIntoConstraints为false
2.初始化控件的时候可以先不用设置frame属性的.
3.使用translatesAutoresizingMaskIntoConstraints之前必须先添加到父View中(也就是如果要对leftView使用自动布局,那么就必须先把leftview添加的它的父view里面,也就是leftView.superView,并且对leftView的约束条件添加到superView上,让superView约束leftView,)
4.第一个约束的意思是leftView的顶部等于父view的顶部的1倍加40
这个需要注意几点:1.这是个二元约束,toItem: 的参数不能为空,并且multiplier也不能为0,否则会报错,错误信息是:
大意是说:乘数为0或者第二个item(也就是view)为空,对第一个item(view)的约束是不合法的.约束条件必须是成对出现.
细心的同学可能注意到了第三个约束,哦....不,第四个.怎么第二个参数是nil啊
let heithL = NSLayoutConstraint(item: leftView, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier:1, constant: 100);
这句代码翻译成"中文"意识就是leftView的高等于100;
好了,剩下的几个自己琢磨一下他们的意思.其实这里是有个公式的的
如果英文比较好的同学建议还是看看官方文档,实在不想看的话,那么就简单看一下下面这个公式:
init(item view1: AnyObject, attribute attr1: NSLayoutAttribute, relatedBy relation: NSLayoutRelation, toItem view2: AnyObject?, attribute attr2: NSLayoutAttribute, multiplier: CGFloat, constant c: CGFloat)
结束语:
祝福你们在IT的iOS的手机开发的工作中越来越牛,哈哈哈...