//之前用storyboard拉过约束觉得特别好用,但是并没有改变我纯代码开发的梦想所以简单的写了个例子
//推荐看官方文档详细全面
//一般约束为4个或者以上(label比较特殊最少2个就够了不用设置其宽高 它会根据字体来调整)所以一般代码约束是当场看不出来对错的写的时候要谨慎
//下面展示个简单的swift的例子 等熟悉了 会写一个用约束来实现label根据内容变化大小的例子
import UIKit
class ViewController: UIViewController {
//定义一个高度的约束
var height:NSLayoutConstraint!
override func viewDidLoad() {
super.viewDidLoad()
buildControl()
// Do any additional setup after loading the view, typically from a nib.
}
/**
界面拖了一个button 链接的点击事件
- parameter sender: button
*/
@IBAction func btnClick(sender: AnyObject) {
//点击按钮改变高度约束
self.height.constant = 200
}
//创建界面、
func buildControl()
{
//创建一个view
let segementPage = UIView()
segementPage.translatesAutoresizingMaskIntoConstraints = false
segementPage.backgroundColor = UIColor.orangeColor()
//这边要先添加到视图然后才可以添加约束
self.view.addSubview(segementPage)
//左 上 右 的约束
let leftC = NSLayoutConstraint.init(item: segementPage, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Leading,multiplier: 1, constant: 0) as NSLayoutConstraint
let topC = NSLayoutConstraint.init(item: segementPage, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0) as NSLayoutConstraint
let rightC = NSLayoutConstraint.init(item: segementPage, attribute: NSLayoutAttribute.Trailing, relatedBy: NSLayoutRelation.Equal, toItem: self.view, attribute: NSLayoutAttribute.Trailing, multiplier: 1, constant: 0) as NSLayoutConstraint
//这边是高度的约束因为没有参照物所以写法有点不同 注意一下
let heightC = NSLayoutConstraint.init(item: segementPage, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 60) as NSLayoutConstraint
//新版的约束添加约束方法 建议使用
// NSLayoutConstraint.activateConstraints([leftC,topC,rightC,heightC])
//单个约束可以用这个
// leftC.active = true
//老版的约束方法
//除了自己的属性高宽等 其它属性(与父视图有交集的地方)应该添加在父视图上
self.view.addConstraints([leftC,topC,rightC])
//设置高度
segementPage.addConstraints([heightC])
//属性外设置来控制view的高度
self.height = heightC
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}