微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

}

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐