iOS中链式编程中最经典的例子是Masonry为代表的代码形式,代码如下:
make.edges.equalTo(superview).with.insets(100);
Objective-C 链式编程
Objective-C中实现链式编程主要是通过Block来实现,利用方法的点式调用,自定义FEHeaderView,定义如下:
@class FEHeaderView;
typedef FEHeaderView *(^FEHeaderBlock)(UIColor *color);
typedef FEHeaderView *(^FEHeaderAssignBlock)(CGFloat num);
@interface FEHeaderView : UIView
- (FEHeaderBlock)bgColor;
- (FEHeaderAssignBlock)borderWidth;
- (FEHeaderBlock)borderColor;
@end
实现如下:
@implementation FEHeaderView
- (FEHeaderBlock)bgColor {
FEHeaderBlock block = ^(UIColor *color) {
self.backgroundColor = color;
return self;
};
return block;
}
- (FEHeaderAssignBlock)borderWidth {
FEHeaderAssignBlock block = ^(CGFloat width) {
self.layer.masksToBounds = YES;
self.layer.borderWidth = width;
return self;
};
return block;
}
- (FEHeaderBlock)borderColor {
FEHeaderBlock block = ^(UIColor *color) {
self.layer.borderColor = color.CGColor;
return self;
};
return block;
}
@end
测试代码:
FEHeaderView *view = [[FEHeaderView alloc] initWithFrame:CGRectMake(100, 200, 100, 100)];
view.bgColor([UIColor grayColor]).borderWidth(3.0).borderColor([UIColor redColor]);
[self.view addSubview:view];
Swift 链式编程
Swift中的实现链式编程比Objective-C中简单很多,通过func和extension即可实现.
扩展UIView:
extension UIView {
func bgColor(color:UIColor) -> UIView {
self.backgroundColor = color
return self
}
func borderColor(color:UIColor) -> UIView {
self.layer.borderColor = color.cgColor
self.layer.masksToBounds = true
return self
}
func borderWidth(width:Float) -> UIView {
self.layer.borderWidth = CGFloat(width)
return self
}
}
测试代码:
let view:UIView = UIView(frame: CGRect(x: 100, y: 200, width: 100, height: 100)).bgColor(color: UIColor.red).borderColor(color: UIColor.gray).borderWidth(width: 5.0)
self.view.addSubview(view)