block的使用:
- 假定已有一个
UIViewController
和一个继承自UIView
的视图TouchView
- 在
TouchView.h
里写下如下代码:
typedef void(^NameBlock)(int i);//参数的个数和类型自己定
@property(nonatomic,copy) NameBlock nameBlock;
-(void)useBlockNameBlock:(NameBlock)nameBlock;
- 在
TouchView.m
里写下如下代码:
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.nameBlock(5);
}
-(void)useBlockNameBlock:(NameBlock)nameBlock{
self.nameBlock = nameBlock;
}
- 在
Controller
的viewDidLoad
里写下如下代码:
TouchView *touchView = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[self.view addSubview:touchView];
touchView.backgroundColor = [UIColor orangeColor];
[touchView useBlockNameBlock:^(int i) {
NSLog(@"%D",i);
}];
- 如果
block
里用到self
,不要忘记加上__weak typeof(self) weakSelf = self
- 如果不想用的
-(void)useBlockNameBlock:(NameBlock)nameBlock
话可以将代码分别下面这样就可以了:
1、touchView.h
typedef void(^NameBlock)(int i);
@property(nonatomic,copy) NameBlock nameBlock;
-(void)setNameBlock:(NameBlock)nameBlock;
2、touchView.m
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
self.nameBlock(5);
}
3、Controller
TouchView *touchView = [[TouchView alloc]initWithFrame:CGRectMake(100, 100, 100, 100)];
[self.view addSubview:touchView];
touchView.backgroundColor = [UIColor orangeColor];
[touchView setNameBlock:^(int i) {
NSLog(@"%D",i);
}];
网友评论