-、由主界面A傳值給子界面B(屬性傳值,方法傳值)
將A界面UITextField上輸入的內容在點擊按鈕的時候傳給B界面中的UITextField
1.屬性傳值
在B界面間定義一個屬性NSString * info,在A中創建B的時候給這個屬性賦值,B中的UITextField來顯示這個infoA 界面
.h中添加一個屬性 @property(nonatomic,retain)UITextField * textField;
.m中-(void)btnAction:(id)sender{SecondViewController * secondViewController = [[SecondViewControlleralloc] init];[secondViewController setInfo:_textField.text];[selfpresentViewController:secondViewController animated:NOcompletion:^{}];[secondViewControllerrelease];
}
B 界面
.h中
添加一個屬性 @property(nonatomic,retain)NSString * info;
.m中
[textField setText:_info];
2.方法傳值
在B界面中添加一個方法-(void)setString:(NSString *)str,A界面創建B界面對象,B對象調用這個方法給NSString * info傳值
A 界面
.h中添加一個屬性 @property(nonatomic,retain)UITextField * textField;
.m中-(void)btnAction:(id)sender{SecondViewController * secondViewController = [[SecondViewController alloc] init];[secondViewControllersetString:_textField.text];[self presentViewController:secondViewController animated:NO completion:^{}];[secondViewController release];}
B 界面
.h中添加一個屬性 @property(nonatomic,retain)NSString * info;
.m中
-(void)setString:(NSString *)str
{
self.info = str;
}
[textField setText:_info];
二、由子界面B返回到主界面A時傳值
1.協議傳值
B界面
.h
//創建一個協議,用來給主界面傳值
@protocol SendToFirstDelegate <NSObject>
-(void)setFirstText:(NSString *)str;
@end
//添加一個屬性
@property(nonatomic,assign)id<SendToFirstDelegate>delegate; //代理變量
.m
-(void)btnAction:(id)sender
{
[self.delegate setFirstText:_textField.text];
[self dismissViewControllerAnimated:NO completion:^{}];
}
A界面
.h
//包含B界面的頭文件,主要時爲了遵循協議
#import "SecondViewController.h"
//遵循協議
@interface FirstViewController : UIViewController<SendToFirstDelegate>
.m中
//實現協議
-(void)setFirstText:(NSString *)str
{
[_textField setText:str];
}
2.消息中心傳值(通常可以跨幾個界面來傳值)
註冊消息中心
[[NSNotificationCenter defaultCenter]addObserver:(id) selector:(SEL)name:(NSString *) object:(id)];
參數說明:
ObServer 觀察者,就是或的消息的對象,一般是self,
selector 獲得消息後執行的方法選擇器(參數是NSNotification *類型的,我們用它的userInfo的數據)
name 消息中心通信的暗號,需要兩邊匹配
object 一般爲nil代表是公共的消息中心
post一個消息
[[NSNotificationCenter defaultCenter]postNotificationName:(NSString *) object:(id) userInfo:(NSDictionary *)];
參數說明
name 消息中心通信的暗號,需要兩邊匹配
useerInfo 傳回的數據,是一個字典類型的
A界面
.m
//init方法裏註冊消息中心
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setText:) name:@"IOS" object:Nil];
//添加消息中心響應方法
-(void)setText:(NSNotification *)noti
{
NSDictionary * dic =[noti userInfo];
[_textField setText:[dic objectForKey:@"text"]];
}
B界面
.m
//按鈕按下之後通過消息中心將info傳給A界面
-(void)btnAction:(id)sender
{
//[self.delegate setFirstText:_textField.text];
NSDictionary * dic = [NSDictionary dictionaryWithObject:_textField forKey:@"text"];
[[NSNotificationCenter defaultCenter]postNotificationName:@"IOS" object:Nil userInfo:dic];
[self dismissViewControllerAnimated:NO completion:^{}];
}