block的传值和使用
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"@implementationAppDelegate-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{self.window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];//Overridepointforcustomizationafterapplicationlaunch.self.window.backgroundColor=[UIColorwhiteColor];[self.windowmakeKeyAndVisible];MainViewController*mainVC=[[MainViewControlleralloc]init];UINavigationController*navVc=[[UINavigationControlleralloc]initWithRootViewController:mainVC];self.window.rootViewController=navVc;//模糊效果navVc.navigationBar.translucent=YES;[navVcrelease];[mainVCrelease];[_windowrelease];returnYES;}-(void)dealloc{[_windowrelease];[superdealloc];}-(void)applicationWillResignActive:(UIApplication*)application{//Sentwhentheapplicationisabouttomovefromactivetoinactivestate.Thiscanoccurforcertaintypesoftemporaryinterruptions(suchasanincomingphonecallorSMSmessage)orwhentheuserquitstheapplicationanditbeginsthetransitiontothebackgroundstate.//Usethismethodtopauseongoingtasks,disabletimers,andthrottledownOpenGLESframerates.Gamesshouldusethismethodtopausethegame.}-(void)applicationDidEnterBackground:(UIApplication*)application{//Usethismethodtoreleasesharedresources,saveuserdata,invalidatetimers,andstoreenoughapplicationstateinformationtorestoreyourapplicationtoitscurrentstateincaseitisterminatedlater.//Ifyourapplicationsupportsbackgroundexecution,thismethodiscalledinsteadofapplicationWillTerminate:whentheuserquits.}-(void)applicationWillEnterForeground:(UIApplication*)application{//Calledaspartofthetransitionfromthebackgroundtotheinactivestate;hereyoucanundomanyofthechangesmadeonenteringthebackground.}-(void)applicationDidBecomeActive:(UIApplication*)application{//Restartanytasksthatwerepaused(ornotyetstarted)whiletheapplicationwasinactive.Iftheapplicationwaspreviouslyinthebackground,optionallyrefreshtheuserinterface.}-(void)applicationWillTerminate:(UIApplication*)application{//Calledwhentheapplicationisabouttoterminate.Savedataifappropriate.SeealsoapplicationDidEnterBackground:.}@end
MainViewController.m
#import"MainViewController.h"#import"SecondViewController.h"@interfaceMainViewController()@end@implementationMainViewController-(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];if(self){//Custominitialization}returnself;}-(void)viewDidLoad{[superviewDidLoad];//Doanyadditionalsetupafterloadingtheview.self.title=@"block传值";UIButton*button=[UIButtonbuttonWithType:UIButtonTypeSystem];button.frame=CGRectMake(120,100,80,30);button.backgroundColor=[UIColormagentaColor];[buttonsetTitleColor:[UIColorwhiteColor]forState:UIControlStateNormal];[buttonsetTitle:@"按钮"forState:UIControlStateNormal];button.layer.cornerRadius=5;[buttonaddTarget:selfaction:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];[self.viewaddSubview:button];}-(void)buttonClicked:(UIButton*)button{//block语法//返回值类型(^block参数名)(参数类型参数名)=^返回值类型(参数类型参数名){//具体实现;//};floatb=0;//1.无参数无返回值void(^block1)(void)=^(void){NSLog(@"可口可乐");};//block语法调用block1();//2.有参数,无返回值void(^block2)(NSString*str1,NSString*str2)=^void(NSString*str1,NSString*str2){NSString*a=[str1stringByAppendingString:str2];NSLog(@"%@",a);};block2(@"abc",@"def");//3.有返回值,无参数NSString*(^block3)(void)=^NSString*(void){return@"咿呀咿呀呦";};NSLog(@"%@",block3());//4.有参数,有返回值NSString*(^block4)(NSString*str1)=^NSString*(NSString*str1){return[str1stringByAppendingString:@"真棒!!!!"];};NSLog(@"%@",block4(@"苹果电脑"));//声明一个block,需要传入一个颜色,让当前的view变色void(^changeColor)(UIColor*color)=^(UIColor*color){self.view.backgroundColor=color;};//block传值------------声明一个void(^changeValue)(UITextField*textField)=^void(UITextField*textField){[buttonsetTitle:textField.textforState:UIControlStateNormal];};NSLog(@"%@",block1);//block的地址在全局区NSLog(@"%@",changeColor);//如果在block的代码中,使用了block外部的变量,系统会把block指针转移到栈区SecondViewController*secondVC=[[SecondViewControlleralloc]init];//block传值---------将block给第二个页面secondVC.block=changeColor;secondVC.blockofValue=changeValue;secondVC.name=button.currentTitle;NSLog(@"%@",button.currentTitle);NSLog(@"%@",secondVC.block);//使用copy后block会被系统转移到堆区[self.navigationControllerpushViewController:secondVCanimated:YES];[secondVCrelease];}-(void)didReceiveMemoryWarning{[superdidReceiveMemoryWarning];//Disposeofanyresourcesthatcanberecreated.}/*#pragmamark-Navigation//Inastoryboard-basedapplication,youwilloftenwanttodoalittlepreparationbeforenavigation-(void)prepareForSegue:(UIStoryboardSegue*)seguesender:(id)sender{//Getthenewviewcontrollerusing[seguedestinationViewController].//Passtheselectedobjecttothenewviewcontroller.}*/@end
SecondViewController.h
#import<UIKit/UIKit.h>@interfaceSecondViewController: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"@interfaceSecondViewController()@property(nonatomic,retain)UITextField*textField;@end@implementationSecondViewController-(id)initWithNibName:(NSString*)nibNameOrNilbundle:(NSBundle*)nibBundleOrNil{self=[superinitWithNibName:nibNameOrNilbundle:nibBundleOrNil];if(self){//Custominitialization}returnself;}-(void)viewDidLoad{[superviewDidLoad];//Doanyadditionalsetupafterloadingtheview.self.view.backgroundColor=[UIColorwhiteColor];self.textField=[[UITextFieldalloc]initWithFrame:CGRectMake(50,100,220,30)];self.textField.borderStyle=UITextBorderStyleRoundedRect;//self.textField.text=self.name;NSLog(@"%@",self.name);self.textField.clearButtonMode=UITextFieldViewModeAlways;[self.viewaddSubview:self.textField];[_textFieldrelease];UIButton*button=[[UIButtonalloc]initWithFrame:CGRectMake(100,180,120,30)];button.backgroundColor=[UIColorcyanColor];[buttonsetTitle:@"点击"forState:UIControlStateNormal];button.layer.cornerRadius=5;[buttonaddTarget:selfaction:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];[self.viewaddSubview:button];}-(void)buttonClicked:(UIButton*)button{//block传值---------将传值给blockNSArray*array=[NSArrayarrayWithObjects:[UIColoryellowColor],[UIColorcyanColor],[UIColorgreenColor],[UIColorbrownColor],nil];self.block([arrayobjectAtIndex:rand()%4]);//block传值---------将传值给blockself.blockofValue(self.textField);[self.navigationControllerpopToRootViewControllerAnimated:YES];}-(void)didReceiveMemoryWarning{[superdidReceiveMemoryWarning];//Disposeofanyresourcesthatcanberecreated.}/*#pragmamark-Navigation//Inastoryboard-basedapplication,youwilloftenwanttodoalittlepreparationbeforenavigation-(void)prepareForSegue:(UIStoryboardSegue*)seguesender:(id)sender{//Getthenewviewcontrollerusing[seguedestinationViewController].//Passtheselectedobjecttothenewviewcontroller.}*/@end
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。