block的传值
1.第一页中声明一个block,需要传入一个颜色,让当前的view变色
//声明一个block,需要传入一个颜色,让当前的view变色
void(^changeColor)(UIColor *color) = ^(UIColor *color){
self.view.backgroundColor = color;
};
2. 第一页中//block传值---------将block给第二个页面
SecondViewController *secondVC = [[SecondViewController alloc] init];
//block传值---------将block给第二个页面
secondVC.block = changeColor;
3.第二页中定义--当block变量作为一个类的属性,必须要使用copy修饰
//block传值---------将block给第二个页面
//block传值 ---当block变量作为一个类的属性,必须要使用copy修饰
@property (nonatomic , copy)void(^block)(UIColor *color);
4.在第二页中给block传值
//block传值---------将传值给block
NSArray *array = [NSArray arrayWithObjects:[UIColor yellowColor], [UIColor cyanColor], [UIColor greenColor], [UIColor brownColor], nil];
self.block([array objectAtIndex:rand() % 4]);
类和文件
AppDelegate.m
#import "AppDelegate.h" #import "MainViewController.h" @implementation AppDelegate - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]]; // Override point for customization after application launch. self.window.backgroundColor = [UIColor whiteColor]; [self.window makeKeyAndVisible]; MainViewController *mainVC = [[MainViewController alloc] init]; UINavigationController *navVc = [[UINavigationController alloc] initWithRootViewController:mainVC]; self.window.rootViewController = navVc; //模糊效果 navVc.navigationBar.translucent = YES; [navVc release]; [mainVC release]; [_window release]; return YES; } - (void)dealloc { [_window release]; [super dealloc]; } - (void)applicationWillResignActive:(UIApplication *)application { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } - (void)applicationDidEnterBackground:(UIApplication *)application { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } - (void)applicationWillEnterForeground:(UIApplication *)application { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } - (void)applicationDidBecomeActive:(UIApplication *)application { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } - (void)applicationWillTerminate:(UIApplication *)application { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } @end
MainViewController.m
#import "MainViewController.h" #import "SecondViewController.h" @interface MainViewController () @end @implementation MainViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.title = @"block传值"; UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem]; button.frame = CGRectMake(120, 100, 80, 30); button.backgroundColor = [UIColor magentaColor]; [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal]; [button setTitle:@"按钮" forState:UIControlStateNormal]; button.layer.cornerRadius = 5; [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)buttonClicked:(UIButton *)button { //block语法 //返回值类型 (^block参数名) (参数类型 参数名) = ^返回值类型 (参数类型 参数名) { //具体实现; //}; float b = 0; //1.无参数无返回值 void(^block1)(void) = ^(void){ NSLog(@"可口可乐"); }; //block语法调用 block1(); //2.有参数,无返回值 void(^block2)(NSString *str1, NSString *str2) = ^void(NSString *str1, NSString *str2){ NSString *a = [str1 stringByAppendingString:str2]; NSLog(@"%@", a); }; block2(@"abc",@"def"); //3.有返回值,无参数 NSString *(^block3)(void) = ^NSString *(void){ return @"咿呀咿呀呦"; }; NSLog(@"%@",block3()); //4.有参数,有返回值 NSString *(^block4)(NSString *str1) =^NSString *(NSString *str1){ return [str1 stringByAppendingString:@"真棒!!!!"]; }; NSLog(@"%@", block4(@"苹果电脑")); //声明一个block,需要传入一个颜色,让当前的view变色 void(^changeColor)(UIColor *color) = ^(UIColor *color){ self.view.backgroundColor = color; }; //block传值------------声明一个 void(^changeValue)(UITextField *textField) = ^void(UITextField *textField){ [button setTitle:textField.text forState:UIControlStateNormal]; }; NSLog(@"%@", block1); //block的地址在全局区 NSLog(@"%@", changeColor); //如果在block的代码中,使用了block外部的变量,系统会把block指针转移到栈区 SecondViewController *secondVC = [[SecondViewController alloc] init]; //block传值---------将block给第二个页面 secondVC.block = changeColor; secondVC.blockofValue = changeValue; secondVC.name = button.currentTitle; NSLog(@"%@", button.currentTitle); NSLog(@"%@", secondVC.block); //使用copy后block会被系统转移到堆区 [self.navigationController pushViewController:secondVC animated:YES]; [secondVC release]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
SecondViewController.h
#import <UIKit/UIKit.h> @interface SecondViewController : UIViewController //block传值---------将block给第二个页面 //block传值 ---当block变量作为一个类的属性,必须要使用copy修饰 @property (nonatomic , copy)void(^block)(UIColor *color); @property (nonatomic , copy)void(^blockofValue)(UITextField *textField); // @property (nonatomic , copy)NSString *name; @end
SecondViewController.m
import "SecondViewController.h" @interface SecondViewController () @property (nonatomic , retain)UITextField *textField; @end @implementation SecondViewController - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil { self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; if (self) { // Custom initialization } return self; } - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. self.view.backgroundColor = [UIColor whiteColor]; self.textField = [[UITextField alloc] initWithFrame:CGRectMake(50, 100, 220, 30)]; self.textField.borderStyle = UITextBorderStyleRoundedRect; // self.textField.text = self.name; NSLog(@"%@",self.name); self.textField.clearButtonMode = UITextFieldViewModeAlways; [self.view addSubview:self.textField]; [_textField release]; UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(100, 180, 120, 30)]; button.backgroundColor = [UIColor cyanColor]; [button setTitle:@"点击" forState:UIControlStateNormal]; button.layer.cornerRadius = 5; [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside]; [self.view addSubview:button]; } - (void)buttonClicked:(UIButton *)button { //block传值---------将传值给block NSArray *array = [NSArray arrayWithObjects:[UIColor yellowColor], [UIColor cyanColor], [UIColor greenColor], [UIColor brownColor], nil]; self.block([array objectAtIndex:rand() % 4]); //block传值---------将传值给block self.blockofValue(self.textField); [self.navigationController popToRootViewControllerAnimated:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } /* #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ @end
本文出自 “小刘_Blog” 博客,请务必保留此出处http://liuyafang.blog.51cto.com/8837978/1551399
原文地址:http://liuyafang.blog.51cto.com/8837978/1551399