Swift基础(十二)UI基础--AutoLayout

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        // 用代码实现自动布局
        let leftButton: UIButton = UIButton(type: UIButtonType.Custom);
        leftButton.backgroundColor = UIColor(red: 0.8, green: 1.0, blue: 0.4, alpha: 1.0);
        self.view.addSubview(leftButton)
        leftButton.tag = 19;
        
        let rightButton: UIButton = UIButton(type: UIButtonType.Custom);
        rightButton.backgroundColor = UIColor(red: 0.8, green: 0.9, blue: 0.3, alpha: 1.0);
        self.view.addSubview(rightButton)
        rightButton.tag = 19;
        
        let bottomButton: UIButton = UIButton(type: UIButtonType.Custom);
        bottomButton.backgroundColor = UIColor(red: 0.4, green: 0.6, blue: 0.8, alpha: 1.0);
        self.view.addSubview(bottomButton)
        bottomButton.tag = 19;
        bottomButton.setTitle("取消", forState: UIControlState.Normal);
        bottomButton.addTarget(self, action: "cancelAutoLayout", forControlEvents: UIControlEvents.TouchUpInside);
        
        // 关闭autoresizingMask转换成约束
        leftButton.translatesAutoresizingMaskIntoConstraints = false
        rightButton.translatesAutoresizingMaskIntoConstraints = false
        bottomButton.translatesAutoresizingMaskIntoConstraints = false
        
        // 创建一个控件数组
        var views: [String : AnyObject] = [String : AnyObject]()
        views["leftButton"] = leftButton;
        views["rightButton"] = rightButton;
        views["bottomButton"] = bottomButton;
        
        // 创建水平方向leftButton、rightButton的约束:从左至右依次为 -> 在水平方向,边界往右20像素为leftButton,leftButton再往右20像素为rightButton,rightButton的宽等于leftButton,rightButton往右20像素为边界
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[leftButton]-20-[rightButton(==leftButton)]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: views));
        
        // 创建水平方向bottomButton的约束:从左至右依次为 -> 在水平方向,边界往右20像素为bottomButton,bottomButton往右20像素为边界
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-20-[bottomButton]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: views));
        
        // 创建竖直方向leftButton、bottomButton的约束:从上到下依次为 -> 在竖直方向上,边界往下40像素为leftButton,leftButton往下20像素为bottomButton,bottomButton的高等于leftButton,bottomButton再往下20像素为边界
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-40-[leftButton]-20-[bottomButton(==leftButton)]-20-|", options: NSLayoutFormatOptions(), metrics: nil, views: views));
        
        // 创建竖直方向rightButton的约束:从上到下依次为 -> 在竖直方向上,边界往下40像素为rightButton,rightButton的高等于leftButton
        self.view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-40-[rightButton(==leftButton)]", options: NSLayoutFormatOptions(), metrics: nil, views: views));

    }

运行结果如图:

Swift基础(十二)UI基础--AutoLayout_第1张图片

Swift基础(十二)UI基础--AutoLayout_第2张图片


你可能感兴趣的:(iOS)