加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

AutoLayout Swift demo

发布时间:2020-12-14 02:04:27 所属栏目:百科 来源:网络整理
导读: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 . blueC

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.

}

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读