UIButton + Category.h

#import <UIKit/UIKit.h>

NS_ASSUME_NONNULL_BEGIN

@interface UIButton (Category)

+ (UIButton *(^)(UIButtonType type, CGRect frame))button;
- (UIButton *(^)(NSString *title))title;
- (UIButton *(^)(UIColor *titleColor))titleColor;
- (UIButton *(^)(id target, SEL selector, UIControlEvents eventType))sel;
@end

NS_ASSUME_NONNULL_END
Copy the code

UIButton + Category.m

#import "UIButton+Category.h"

@implementation UIButton (Category)

+ (UIButton * _Nonnull (^)(UIButtonType, CGRect))button {
    
    return ^(UIButtonType t, CGRect f) {
        
        UIButton *button = [UIButton buttonWithType:t];
        button.frame = f;
        return button;
    };
}

- (UIButton * _Nonnull (^)(NSString *))title {
    
    return ^(NSString *t) {
        
        [self setTitle:t forState:UIControlStateNormal];
        return self;
    };
}

- (UIButton * _Nonnull (^)(UIColor *))titleColor {
    
    return ^(UIColor *tc) {
        
        [self setTitleColor:tc forState:UIControlStateNormal];
        return self;
    };
}

- (UIButton * _Nonnull (^)(id _Nonnull, SEL _Nonnull, UIControlEvents))sel {
    
    return ^(id t, SEL s, UIControlEvents e) {
        
        [self addTarget:t action:s forControlEvents:e];
        return self;
    };
}

@end
Copy the code

use

#import "ViewController.h"
#import "UIButton+Category.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIButton *btn = UIButton.button(UIButtonTypeCustom, CGRectMake(100, 100, 300, 50))
                            .title(@"button title")
                            .titleColor([UIColor redColor])
                            .sel(self, @selector(test), UIControlEventTouchUpInside);
    [self.view addSubview:btn];
}

- (void)test {
    
    NSLog(@"Test");
}

@end
Copy the code