AutoLayout Swift demo

前端之家收集整理的这篇文章主要介绍了AutoLayout Swift demo前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

import UIKit

import Swift



class ViewController: UIViewController {


override func viewDidLoad() {

super.viewDidLoad()

let v1 = UIView()

let v2 = UIView()

v1.backgroundColor = UIColor.redColor()

v2.backgroundColor = UIColor.blueColor()

//遵循autolayout抛弃原有的宽和高

v1.translatesAutoresizingMaskIntoConstraints = true

v2.translatesAutoresizingMaskIntoConstraints = false

view.addSubview(v1)

view.addSubview(v2)

//item1 =(>=,<=) item2*multiplier + constant

//如果是一元约束的话就是,只针对自己的约束,如果是二元约束的话就必须添加在他们最近的共同父视图上

//set v1's height and width

v1.addConstraint(NSLayoutConstraint(item: v1,attribute: .Width,relatedBy: .Equal,toItem: nil,attribute: .NotAnAttribute,multiplier: 1,constant: 100))//v1 = m*0 + constant

//v1.addConstraint(NSLayoutConstraint(item: v1,attribute: .Height,relatedBy: .Equal,toItem: nil,attribute: .NotAnAttribute,multiplier: 1,constant: 100))

//set relationship between topView and v1

view.addConstraint(NSLayoutConstraint(item: v1,attribute: .Left,toItem: view,attribute: .Leading,constant: 20))

view.addConstraint(NSLayoutConstraint(item: v1,attribute: .CenterY,constant: 0))

//set v2's height and width

view.addConstraint(NSLayoutConstraint(item: v2,toItem: v1,multiplier: 1,constant: 0))

view.addConstraint(NSLayoutConstraint(item: v2,attribute: .Height,36)"> //set relationship between v1 and v2

view.addConstraint(NSLayoutConstraint(item: v2,attribute: .Right,constant: 100))

view.addConstraint(NSLayoutConstraint(item: v1,toItem: v2,constant: 0))

}


override func didReceiveMemoryWarning() {

super.didReceiveMemoryWarning()

// Dispose of any resources that can be recreated.

}

}

猜你在找的Swift相关文章