ios开发传值方式

2025-11-02 11:28:12

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>   

@  class  UserEntity;  

  

@protocol PassValueDelegate <NSObject>  

  

-(  void )passValue:(UserEntity *)value;  

  

@end  

在第一个窗口实现协议:

#import <UIKit/UIKit.h>   

#import "PassValueDelegate.h"   

  

//第一个窗口遵守PassValueDelegate   

@interface ViewController : UIViewController<PassValueDelegate>  

  

@property (retain, nonatomic) IBOutlet UILabel *nameLabel;  

@property (retain, nonatomic) IBOutlet UILabel *ageLabel;  

@property (retain, nonatomic) IBOutlet UILabel *gendarLabel;  

  

- (IBAction)openBtnClicked:(id)sender;  

  

@end  

.m文件中实现协议的方法:

[cpp]view plaincopy 

//实现协议,在第一个窗口显示在第二个窗口输入的值方法   

-(  void )passValue:(UserEntity *)value  

{  

    self.nameLabel.text = value.userName;  

    self.ageLabel.text = [NSString stringWithFormat:@  "%d" ,value.age];  

    self.gendarLabel.text = value.gendar;  

}  

点击Open按钮所触发的事件:

[cpp]view plaincopy 

//点击进入第二个窗口的方法   

- (IBAction)openBtnClicked:(id)sender {  

    SecondViewController *secondView = [[SecondViewController alloc] initWithNibName:@  "SecondViewController"  bundle:[NSBundle mainBundle]];  

      //设置第二个窗口中的delegate为第一个窗口的self   

    secondView.delegate = self;  

      

    [self.navigationController pushViewController:secondView animated:YES];  

}  

第二个窗口中声明一个NSObject对象,该对象遵守PassValueDelegate协议:

[cpp]view plaincopy 

#import <UIKit/UIKit.h>   

#import "PassValueDelegate.h"   

  

@interface SecondViewController : UIViewController  

  

@property (retain, nonatomic) IBOutlet UITextField *nameTextField;  

@property (retain, nonatomic) IBOutlet UITextField *ageTextFiled;  

@property (retain, nonatomic) IBOutlet UITextField *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 = [[UserEntity alloc] init];  

    userEntity.userName = self.nameTextField.text;  

    userEntity.gendar = self.gendarTextField.text;  

    userEntity.age = [self.ageTextFiled.text intValue];  

      

      //通过委托协议传值   

    [self.delegate passValue:userEntity];  

      //退回到第一个窗口   

    [self.navigationController popViewControllerAnimated:YES];  

      

    [userEntity release];  

}  

以上就实现了使用Delegate在两个ViewController之间传值,这种场景一般应用在进入子界面输入信息,完后要把输入的信息回传给前一个界面的情况,比如修改用户个人信息,点击修改进入修改界面,修改完后到显示界面显示修改后的结果。

4、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 ]);

类和文件

#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

{

// 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

@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

{

// 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  

static singleton *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;

}

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢