swift 约束,swift版本的UIView+AutoLayout,简单方便,比snapKit好用、方便、简单

话说swift已经更新到4.0了,对于一个资深object-c开发者来说,感觉又是期望也是无奈。总得要学习swift吧,学吧又没多大时间,语法还怪异(个人观点哈)。在新的swift项目中,用到了约束,但是在这么多年的oc书写中,本人一直用的更轻量级的UIView+AutoLayout,使用起来很是方便,个人觉得,比masonry好用哈。但是swift版本中作者并没有更新,主要考虑snapkit不好用,而且还存在bug,因此果断放弃,仿照oc版进行swift编写。
当然了,主要是为了学习和熟悉语法,还有就是用着方便哈。
附上下载链接UIView+AutoLayout

使用起来其实更oc是一样的,但是为了方便区别和语法的不同,这里稍微解释一下:

  • 相对父视图居中,设置大小
let firstView = UIView()
firstView.backgroundColor = UIColor.red
self.view.addSubview(firstView)
firstView.ym_autoCenterInSuperview()
firstView.ym_autoSetDimensionsToSize(size: CGSize(width: 100, height: 100))
  • 相对其他view的位置和父视图的距离
let firstViewLabel = UILabel()
firstViewLabel.text = "firstViewLabel"
firstViewLabel.numberOfLines = 0
firstView.addSubview(firstViewLabel)
//左右两边距离父控件各为12,且垂直居中
firstViewLabel.ym_autoPinEdgeToSuperviewEdge(edge: .ALEdgeLeft, inset: 12)
firstViewLabel.ym_autoPinEdgeToSuperviewEdge(edge: .ALEdgeRight, inset: 12)
firstViewLabel.ym_autoAlignAxisToSuperviewAxis(axis: .ALAxisVertical)
//不设置高度会自动布局
firstViewLabel.ym_autoSetDimensionToSize(dimension: .ALDimensionHeight, size: 20)
  • 设置宽高的比例
let fisrtViewLabel2 = UILabel()
fisrtViewLabel2.text = "第二个label2"
fisrtViewLabel2.textColor = UIColor.green
firstView.addSubview(fisrtViewLabel2)
//fisrtViewLabel2的宽度与firstViewLabel的宽度一样,高度是firstViewLabel的1.2倍,并且再同一垂直线上,顶部距离firstViewLabel的底部距离为5
fisrtViewLabel2.ym_autoMatchDimensionToDimensionOfView(dimension: .ALDimensionWidth, toDimension: .ALDimensionWidth, peerView: firstViewLabel)
fisrtViewLabel2.ym_autoMatchDimensionToDimensionOfViewWithMultiplier(dimension: .ALDimensionHeight, toDimension: .ALDimensionHeight, peerView: firstViewLabel, multiplier: 1.2)
fisrtViewLabel2.ym_autoAlignAxisToSameAxisOfView(axis: .ALAxisVertical, peerView: firstViewLabel)
fisrtViewLabel2.ym_autoPinEdgeToEdgeOfViewWithOffset(edge: .ALEdgeTop, toEdge: .ALEdgeBottom, peerView: firstViewLabel, offset: 5)
  • 约束可以持有,方便后期改变约束
let secondView = UIView()
self.secondView = secondView
secondView.backgroundColor = UIColor.purple
self.view.addSubview(secondView)
///约束持有,后期动画改变secondView的高度
self.secondViewHeightConstraint = secondView.ym_autoSetDimensionToSize(dimension: .ALDimensionHeight, size: 200)
secondView.ym_autoPinEdgeToSuperviewEdge(edge: .ALEdgeLeft, inset: 0)
secondView.ym_autoPinEdgeToSuperviewEdge(edge: .ALEdgeRight, inset: 0)
secondView.ym_autoPinEdgeToEdgeOfViewWithOffset(edge: .ALEdgeTop, toEdge: .ALEdgeBottom, peerView: firstView, offset: 10)

其他API就不一一列出来了,小伙伴们可以去下载来看看哈!有问题及时留言给我哈!尽量第一时间回复!谢谢
重要的事情再来一遍哈,下载地址

各位小伙伴,喜欢的记得给个start哈,再点个赞呗!!!

你可能感兴趣的:(swift 约束,swift版本的UIView+AutoLayout,简单方便,比snapKit好用、方便、简单)