您的位置:首页 > 产品设计 > UI/UE

block自定义UIButton

2016-07-04 21:31 501 查看
ViewController
- (void)viewDidLoad
{
[super viewDidLoad];

MyButton *button = [MyButton buttonWithType:UIButtonTypeSystem];
button.frame = CGRectMake(20, 50, 280, 50);
button.backgroundColor = [UIColor redColor];
[self.view addSubview:button];

//实现button的block回调
[button setButtonShouldBlock:^(MyButton *sender) {
NSLog(@"我是Block: should方法\n");
}];

[button setButtonWillBlock:^(MyButton *sender) {
NSLog(@"我是Block: Will方法\n");
}];

[button setButtonDidBlock:^(MyButton *sender) {
NSLog(@"我是Blcok: Did方法\n");
}];

}


@interface MyButton :
UIButton
typedef void (^ButtonWillBlock)(MyButton *sender);
typedef void (^ButtonDidBlock)(MyButton *sender);
typedef void (^ButtonShouldBlock)(MyButton *sender);

@property (nonatomic, copy) ButtonWillBlock willBlock;
@property (nonatomic, copy) ButtonDidBlock didBlock;
@property (nonatomic, copy) ButtonShouldBlock shouldBlock;

//接受block的方法
-(void)setButtonShouldBlock: (ButtonShouldBlock) block;
-(void)setButtonWillBlock: (ButtonWillBlock) block;
-(void)setButtonDidBlock:(ButtonDidBlock) block;

//接受block块
-(void)setButtonShouldBlock: (ButtonShouldBlock) block
{
self.shouldBlock = block;
[self addTarget:self action:@selector(buttonClick) forControlEvents:UIControlEventTouchUpInside];
}

-(void)setButtonWillBlock: (ButtonWillBlock) block
{
self.willBlock = block;
}

-(void)setButtonDidBlock:(ButtonDidBlock) block
{
self.didBlock = block;
}

- (void)buttonClick
{
if (_shouldBlock)
{
_shouldBlock(self);
NSLog(@"调用了");
self.backgroundColor = [UIColor grayColor];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: