Masonry在oc下使用很方便,但是在swift下,由于oc方法和property都可以使用.fuc的语法,swift下只有属性可以使用.property的语法,方法只能写成.func().因此在swift下如果直接写就只能写成
downTriangle.mas_makeConstraints { (make: MASConstraintMaker? ) in
_ = make?.left.equalTo()(self)
_ = make?.bottom.equalTo()(self)
}
skillTypeText.mas_makeConstraints {
_ = $?.top.left.equalTo()(self.containerView)?.with().offset()()
let size = NSValue(cgSize: CGSize(width:, height:))
_ = $?.size.equalTo()(size)
}
这种写法非常麻烦,也不自然。如果直接使用snapkit又需要引入新的库,所以楼主就对masonry做了些改动。改动后的写法:
downTriangle.mas_makeConstraints {
$.left.sEqualTo(self)
$.bottom.sEqualTo(self)
}
对于mas_equalTo则可以写成:
skillTypeText.mas_makeConstraints {
$.top.left.sEqualTo(self.containerView).with().sOffset()
// let size = NSValue(cgSize: CGSize(width:30, height:15))
$.size.sEqualTo(size: CGSize(width:, height:))
}
主要改动了以下几个地方:
1.mas_makeConstraints 及类似方法添加__nonnull的声明
- (NSArray *)mas_makeConstraints:( void(^ _Nonnull )(MASConstraintMaker* __nonnull make))block;
2.Masconstraint添加属性声明,本来是想写个category添加个声明,但是失败了,好像只能写在原文件上。
@property (nonatomic, strong, readonly) MASConstraint *left;
@property (nonatomic, strong, readonly) MASConstraint *top;
@property (nonatomic, strong, readonly) MASConstraint *right;
@property (nonatomic, strong, readonly) MASConstraint *bottom;
@property (nonatomic, strong, readonly) MASConstraint *leading;
@property (nonatomic, strong, readonly) MASConstraint *trailing;
@property (nonatomic, strong, readonly) MASConstraint *width;
@property (nonatomic, strong, readonly) MASConstraint *height;
@property (nonatomic, strong, readonly) MASConstraint *centerX;
@property (nonatomic, strong, readonly) MASConstraint *centerY;
@property (nonatomic, strong, readonly) MASConstraint *baseline;
3.swift下添加sEqualTo,sInset等方法
extension MASConstraint{
@discardableResult
func sEqualTo(_ attr : Any?) -> MASConstraint!{
return self.equalTo()(attr)
}
@discardableResult
func sEqualTo( point : CGPoint) -> MASConstraint!{
let value = NSValue(cgPoint:point)
return self.equalTo()(value)
}
@discardableResult
func sEqualTo( size : CGSize) -> MASConstraint!{
let value = NSValue(cgSize:size)
return self.equalTo()(value)
}
@discardableResult
func sEqualTo( inset : UIEdgeInsets) -> MASConstraint!{
let value = NSValue(uiEdgeInsets:inset)
return self.equalTo()(value)
}
@discardableResult
func sOffset(_ offset : CGFloat) -> MASConstraint!{
return self.offset()(offset)
}
@discardableResult
func sInset(_ inset : UIEdgeInsets) -> MASConstraint!{
return self.insets()(inset)
}
}
masonry使用的各类方法有很多,楼主的项目也很赶,一般也是遇到一个写一个。大致改法都类似。像nsarray+masaddition基本没用,也没必要去添加。