ios block 学习

2016-11-22  本文已影响0人  倔强的仙人掌

敲代码快一周年了,项目没有用过block惭愧留下学习心得;

我这了解的比较浅显;基本语法 , 返回值类型(^变量名)(参数)=^(参数){ 执行的代码块};

1,无返回值无参数类型

- (void)viewDidLoad {

[super viewDidLoad];

void(^changeName)()=^(){

NSLog(@"无返回值,无参数");

};

changeName();

}

2,无返回值有参数

- (void)viewDidLoad {

[super viewDidLoad];

void(^changeName)(int , int)=^(int a ,int b){

NSLog(@"结果为%d",a+b);

};

changeName(2,3);

}

3,有返回值,有参数

//返回整形数据

int (^changeName)(int , int)= ^(int a ,int b){

return a+b;

};

changeName(2,3);

//返回对象类型

NSString* (^changeName)(int , int)= ^(int a ,int b){

NSString *string = [NSString stringWithFormat:@"%d",a+b];

return string;

};

NSString *str = changeName(2,3);

还有一种用法自定义一个block数据类型  在Viewcontroller2中改变Viewcontroller的页面颜色

ViewController2.h文件

@interface ViewController2 : UIViewController

typedef void(^changeColor)(id);  //定义一种block类型

@property (nonatomic, copy)  changeColor backgroundColor;//声明这种类型的对象

@end

ViewController2.m文件

- (void)touchesBegan:(NSSet*)touches withEvent:(UIEvent *)event {

UIColor *color = [UIColor redColor];

self.backgroundColor(color);

}

ViewController.h

- (void)viewDidLoad {

[super viewDidLoad];

ViewController2 *vc= [[ViewController2 alloc]init];

//回调修改颜色

vc.backgroundColor = ^(UIColor *color){

self.view.backgroundColor = color;

};

}

上一篇 下一篇

猜你喜欢

热点阅读