项目中可能须要代码作约束,你们通常都使用三方的Masonry、snapKit(swift使用)等方式,stroyboard就不说了。苹果给咱们提供了一套本身的约束封装,其实也挺好的。若是你要写一套框架,或者封装一个类之类的用到了自动布局,那不要再用三方的了。尽量独立完整,这时候苹果的约束就尤其重要。直接上代码吧!git
//两个viewgithub
let blueBlock = UIView()swift
let orangeBlock = UIView()框架
//这两句必须写ide
blueBlock.translatesAutoresizingMaskIntoConstraints = false布局
orangeBlock.translatesAutoresizingMaskIntoConstraints = falseui
//颜色设置code
blueBlock.backgroundColor = UIColor.blueit
orangeBlock.backgroundColor = .orangegui
//和snp同样先加入
view.addSubview(blueBlock)
view.addSubview(orangeBlock)
/*
四个可约束环境
leadingAnchor
topAnchor
widthAnchor
heightAnchor
此句: equalTo: 相对于谁作约束, constant: 10(意思就是加10)
此句: .isActive = true //开启这个约束(不可省略,只有开启了才算有意义)
guide是我写的一个分类属性,能够是相对于safe area 也能够是相对于父视图view
*/
blueBlock.leadingAnchor.constraint(equalTo: guide.leadingAnchor, constant: 10).isActive = true
blueBlock.topAnchor.constraint(equalTo: guide.topAnchor, constant: 10).isActive = true
blueBlock.widthAnchor.constraint(equalToConstant: 100).isActive = true
blueBlock.heightAnchor.constraint(equalToConstant: 100).isActive = true
到这里第一个view的约束已经作完了,写完试试吧!为了看到相对的效果这里是完整的demo能够下载看看:
https://github.com/caoge9/Cons.git