手抄报 安全手抄报 手抄报内容 手抄报图片 英语手抄报 清明节手抄报 节约用水手抄报

ios开发传值方式

时间:2025-01-04 14:35:25

1、1:属性传值第一步需要用到什么类型就定义什么样的属性 从上一个页面到一个页面的选中方法里面将要传的值传到来(上一个页面)备注:这种方法只适用于上一个页面推到下一个页面MainViewController与SecondViewController两个视图控制器,点击MainViewController中的按钮将跳转到SecondViewController视图,同时想要传递一个值过去。这时可以利用属性传值。首先SecondViewController视图中需要有一个属性用来存储传递过来的值:@property(nonatomic,retain) NSString *firstValue;//属性传值然后MainViewController视图需要引用SecondViewController视图的头文件,在视图中的按钮点击事件中,通过SecondViewController的对象将需要传递的值存在firstValue中:-(void)buttonAction:(UIButton *)button{SecondViewController *second = [[SecondViewController alloc]init];//用下一个视图的属性接受想要传过去的值,属性传值second.firstValue = _txtFiled.text;[self.navigationController pushViewController:second animated:YES];}页面跳转之后,就能在SecondViewController视图中,通过存值的属性,取用刚才传递过来的值://显示传过来的值[_txtFiled setText:_firstValue];//firstValue保存传过来的值

2、方法传值:需求同一中的属性传值一样,但是要通过使用方法传值,可以直接将方法与初始化方法合并,此时当触发MainViewController的按钮点击事件并跳转到SecondViewController时,在按钮点击事件中可以直接通过SecondViewController的初始化,将值保存在firstValue中:初始化方法如下: 首先SecondViewController视图中需要有一个属性用来存储传递过来的值:@property(nonatomic,retain) NSString *firstValue;//传值用//重写初始化方法,用于传值- (id)initWithValue:(NSString *)value{ if(self = [super initWithNibName:nil bundle:nil]) { self.firstValue = value; } return self;}方法传值:- (void)buttonAction:(UIButton *)button{//将方法传值与初始化写到一起SecondViewController *second = [[SecondViewController alloc]initWithValue:_txtFiled.text];//此时已经将值存在firstValue中[self.navigationController pushViewController:second animated:YES];}这样就可以直接通过firstValue属性获得传递过来的值://显示传过来的值[_txtFiled setText:_firstValue];//firstValue保存传过来的值

3、协议传值 代替协议代理传值,主要时间点问题。上面中说明了如何从A传值到B,这次要讲的是如何从A进入B,在B输入值后回传给A,这类似于Android中的利用Activity的onActivityResult回调方法实现两个Activity之间的值传递,那么在IOS中如何实现这个功能呢,答案是使用Delegate(委托协议)。协议中声明的方法:copy#import<Foundation/Foundation.h>@classUserEntity;@protocolPassValueDelegate<NSObject>-(void)passValue:(UserEntity*)value;@end 在第一个窗口实现协议:#import<UIKit/UIKit.h>#import"PassValueDelegate.h"//第一个窗口遵守PassValueDelegate@interfaceViewController:UIViewController<PassValueDelegate>@property(retain,nonatomic)IBOutletUILabel*nameLabel;@property(retain,nonatomic)IBOutletUILabel*ageLabel;@property(retain,nonatomic)IBOutletUILabel*gendarLabel;-(IBAction)openBtnClicked:(id)sender;@end.m文件中实现协议的方法:[cpp]view plaincopy//实现协议,在第一个窗口显示在第二个窗口输入的值方法-(void)passValue:(UserEntity*)value{self.nameLabel.text=value.userName;self.ageLabel.text=[NSStringstringWithFormat:@"%d",value.age];self.gendarLabel.text=value.gendar;}点击Open按钮所触发的事件:[cpp]view plaincopy//点击进入第二个窗口的方法-(IBAction)openBtnClicked:(id)sender{SecondViewController*secondView=[[SecondViewControlleralloc]initWithNibName:@"SecondViewController"bundle:[NSBundlemainBundle]];//设置第二个窗口中的delegate为第一个窗口的selfsecondView.delegate=self;[self.navigationControllerpushViewController:secondViewanimated:YES]; }第二个窗口中声明一个NSObject对象,该对象遵守PassValueDelegate协议:[cpp]view plaincopy#import<UIKit/UIKit.h>#import"PassValueDelegate.h"@interfaceSecondViewController:UIViewController@property(retain,nonatomic)IBOutletUITextField*nameTextField;@property(retain,nonatomic)IBOutletUITextField*ageTextFiled;@property(retain,nonatomic)IBOutletUITextField*gendarTextField;//这里用assign而不用retain是为了防止引起循环引用。@property(nonatomic,assign)NSObject<PassValueDelegate>*delegate;-(IBAction)okBtnClicked:(id)sender;-(IBAction)closeKeyboard:(id)sender;@end输入完毕后,点击OK按钮所触发的事件:[cpp]view plaincopy-(IBAction)okBtnClicked:(id)sender{UserEntity*userEntity=[[UserEntityalloc]init];userEntity.userName=self.nameTextField.text;userEntity.gendar=self.gendarTextField.text;userEntity.age=[self.ageTextFiled.textintValue];//通过委托协议传值[self.delegatepassValue:userEntity];//退回到第一个窗口[self.navigationControllerpopViewControllerAnimated:YES];[userEntityrelease];}以上就实现了使用Delegate在两个ViewController之间传值,这种场景一般应用在进入子界面输入信息,完后要把输入的信息回传给前一个界面的情况,比如修改用户个人信息,点击修改进入修改界面,修改完后到显示界面显示修改后的结果。

4、Block传值 1.第一页中声明一个block,需要传入一个颜色,让当前的view变色//声明一个block,需要传入一个颜色,让当前的view变色void(^changeColor)(UIColor*color) = ^(UIColor*color){self.view.backgroundColor= color;};2.第一页中//block传值---------将block给第二个页面SecondViewController*secondVC = [[SecondViewControlleralloc]init];//block传值---------将block给第二个页面secondVC.block= changeColor;3.第二页中定义--当block变量作为一个类的属性,必须要使用copy修饰//block传值---------将block给第二个页面//block传值---当block变量作为一个类的属性,必须要使用copy修饰@property(nonatomic,copy)void(^block)(UIColor*color);4.在第二页中给block传值//block传值---------将传值给blockNSArray*array = [NSArrayarrayWithObjects:[UIColoryellowColor], [UIColorcyanColor], [UIColorgreenColor], [UIColorbrownColor],nil];self.block([arrayobjectAtIndex:rand() %4]);类和文件#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];returnYES;}- (void)dealloc{[_window release];[superdealloc];}- (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:.}@endMainViewController.m#import "MainViewController.h"#import "SecondViewController.h"@interface MainViewController ()@end@implementation MainViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{self = [superinitWithNibName:nibNameOrNil bundle:nibBundleOrNil];if(self) {// Custom initialization}returnself;}- (void)viewDidLoad{[superviewDidLoad];// 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{[superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}/*#pragma mark - Navigation{// Get the new view controller using [segue destinationViewController].// Pass the selected object to the new view controller.}*/@endSecondViewController.h#import <UIKit/UIKit.h>@interface SecondViewController : UIViewController@property (nonatomic , copy)void(^block)(UIColor *color);@property (nonatomic , copy)void(^blockofValue)(UITextField *textField);//@property (nonatomic , copy)NSString *name;@endSecondViewController.mimport"SecondViewController.h"@interface SecondViewController ()@property (nonatomic , retain)UITextField *textField;@end@implementation SecondViewController- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{self = [superinitWithNibName:nibNameOrNil bundle:nibBundleOrNil];if(self) {// Custom initialization}returnself;}- (void)viewDidLoad{[superviewDidLoad];// 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传值---------将传值给blockNSArray *array = [NSArray arrayWithObjects:[UIColor yellowColor], [UIColor cyanColor], [UIColor greenColor], [UIColor brownColor], nil];self.block([array objectAtIndex:rand() % 4]);//block传值---------将传值给blockself.blockofValue(self.textField);[self.navigationController popToRootViewControllerAnimated:YES];}- (void)didReceiveMemoryWarning{[superdidReceiveMemoryWarning];// Dispose of any resources that can be recreated.}/*#pragma mark - Navigation{// Get the new view controller using [segue destinationViewController].// Pass the selected object to the new view controller.}*/@end

5、5单例传值单例只会对某个类实例化一次/单例类,对单例这个类实例化一次有且仅有一个对象你单例初始化,只能初始化一次,然后你指向的对象,其实都是指向一个内存地址,也就是同一块内存,所以都是一样的/那么,只能有一个对象,就是实例化的那个(1)定义单例类singleton .h文件#import <Foundation/Foundation.h> @interface singleton : NSObject //步骤一//@property (strong,nonatomic) UITextField *value;//最开始的时候把这个value定义为UITextField了,然后在init里面又没有初始化它,就取不到值。任何对象都要初始化它才能使用。 @property (strong, nonatomic) NSString *value; //+(id)shareData: +(singleton *)shareData; //步骤二@end//.m文件#import "singleton.h" @implementation singleton staticsingleton *singletonData = nil; //步骤三+(singleton *)shareData { //步骤四static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ singletonData = [[singleton alloc] init]; }); return singletonData; } -(id)init { //步骤五if (self = [super init]) { // self.value = [[UITextField alloc]init]; } return self; } @end //以上是一个完整单例子(2)ViewController#import <UIKit/UIKit.h>#import "OneViewController.h"#import "singleton.h" //引用单例@interface ViewController : UIViewController@property (weak, nonatomic) IBOutlet UITextField *qqTextfield;- (IBAction)go:(id)sender;@end- (IBAction)go:(id)sender {//单例的使用singleton *oneS = [singleton shareData];// oneS.value.text = self.qqTextfield.text;oneS.value = self.qqTextfield.text;OneViewController *oneVC = [[OneViewController alloc]init];[self presentViewController:oneVC animated:YES completion:nil];}(3)OneViewController#import <UIKit/UIKit.h>#import "singleton.h"@interface OneViewController : UIViewController@property (weak, nonatomic) IBOutlet UITextField *oneTextField;@end- (void)viewDidLoad{[super viewDidLoad];// Do any additional setup after loading the view from its nib.self.oneTextField.text = [singleton shareData].value;}

© 手抄报圈