平常一些简化重复的代码
import SnapKit
extension ConstraintMaker {
func equalToPreTop(preView: UIView?, offset: CGFloat, topOffset: CGFloat? = nil) {
if let preView = preView {
self.top.equalTo(preView.snp.bottom).offset(offset)
} else {
if let topOffset = topOffset, topOffset != 0 {
self.top.equalToSuperview().offset(topOffset)
} else {
self.top.equalToSuperview()
}
}
}
func equalToPreLeft(preView: UIView?, offset: CGFloat, leftOffset: CGFloat? = nil) {
if let preView = preView {
self.left.equalTo(preView.snp.right).offset(offset)
} else {
if let leftOffset = leftOffset, leftOffset != 0 {
self.left.equalToSuperview().offset(leftOffset)
} else {
self.left.equalToSuperview()
}
}
}
func equalToMargins( _ margin: CGFloat) {
self.left.equalTo(margin)
self.right.equalTo(-margin)
}
func equalToBottomLess(show: Bool?, margin: CGFloat) {
if show == true {
self.bottom.lessThanOrEqualToSuperview().offset(-margin)
}
}
}
使用在一些for循环出来添加到view上的场景
A
|
B
|
C
// 上下排列的样式
var topView: UIView? = nil
for i in (0..<10) {
let item = UIView()
self.addSubView(item)
item.snp.makeConstraints { make in
// 具体相邻的顶部的view的bottom距离为10,如果没有顶部的view,等于父view的顶部20的距离
make.equalToPreTop(preView: topView, offset: 10, topOffset: 20)
// 距离左右15的距离
make.equalToMargins(margin: 15)
make.height.equalTo(20)
}
topView = item
}
E-F-G
// 左右排列的样式
var leftView: UIView? = nil
for i in (0..<10) {
let item = UIView()
self.addSubView(item)
item.snp.makeConstraints { make in
// 具体相邻的顶部的view的右侧距离为10,如果没有左部的view,等于父view的左部20的距离
make.equalToPreLeft(leftView: leftView, offset: 10, leftOffset: 20)
make.width(80)
make.height.equalTo(20)
}
leftView = item
}
网友评论