block语法在iOS中应用越来越广,今天大致讲一下Block的用法,主要以回调为主。
大致分几个步骤实现:(以写一个BUtton的回调来说)
1⃣️:声明一个Block和暴露一个接口给外面,并且定义一个property
#import <UIKit/UIKit.h>
//声明一个Block
typedef void (^myBlock)(void);
@interface NewButton : UIButton
@property(nonatomic,strong)myBlock block;
//暴露一个接口给外面
-(void)addTarget:(id)target Andaction:(myBlock)block forControlEvents:(UIControlEvents)controlEvents;
@end
2⃣️:实现方法,并在button被点击的时候触发这个Block。#import "NewButton.h"
@implementation NewButton
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
-(void)addTarget:(id)target Andaction:(myBlock)block forControlEvents:(UIControlEvents)controlEvents{
_block = block;
[self addTarget:self action:@selector(editBtn:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)editBtn:(id)sender{
_block();
}
3⃣️:调用Button,触发回调。@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
NewButton *button = [NewButton buttonWithType:UIButtonTypeRoundedRect];
button.backgroundColor = [UIColor greenColor];
[button setTitle:@"Pressed" forState:UIControlStateNormal];
[button setFrame:CGRectMake(110, 100, 100, 100)];
[self.view addSubview:button];
[button addTarget:self Andaction:^{
NSLog(@"PRESSED");
} forControlEvents:UIControlEventTouchUpInside];
}
[self addTarget:self action:@selector(editBtn:) forControlEvents:UIControlEventTouchUpInside];
这个addTarget:后面是Self,而不是Target,这个Mark一下,纠结我20分钟,蛋碎。