在開發(fā)中最最常用的無非就是界面間的互相傳值了胖缤,今天為大家介紹最常用的三種傳值方法: 協(xié)議 眷蚓、 Block澳骤、 通知中心 F缜俊!为肮!
首先創(chuàng)建第二頁與第三頁以及基礎(chǔ)的button摊册,label,textField等控件颊艳,這里不做過多介紹
1.首先我們來看協(xié)議傳值
(在第二頁textField中輸入文字茅特,點擊上一頁按鈕忘分,將輸入的文字傳到第一頁的textField上)
具體步驟:
1.在第二頁的.h文件中聲明協(xié)議方法
@protocol passValueDelegate <NSObject>
- (void)passContent:(NSString *)content;
@end
2.在第二頁的.h文件中聲明代理人屬性
@property(nonatomic, assign)id<passValueDelegate>delegate;
3.在第二頁.m文件的返回上一頁按鈕的點擊方法里命令代理人執(zhí)行協(xié)議方法
- (void)didClickedBackButton:(UIButton *)button
{
[self.delegate passContent:self.textField.text];
[self.navigationController popToRootViewControllerAnimated:YES];
}
4.在第一頁的.m文件中簽協(xié)議
@interface ViewController ()<passValueDelegate>
5.在第一頁.m文件進(jìn)入下一頁的按鈕點擊方法里設(shè)置代理人
- (void)didClickedButton:(UIButton *)button
{
SecondViewController *svc = [SecondViewController new];
svc.delegate = self;
[self.navigationController pushViewController:svc animated:YES];
}
6.在第一頁.m文件中執(zhí)行協(xié)議方法
- (void)passContent:(NSString *)content
{
self.textField.text = content;
}
點擊上一頁按鈕回到第一頁時,相應(yīng)的文字就傳過來了
Block傳值
具體步驟 (熟練應(yīng)用后1白修、2兩步可以寫在一起)
1.在第三頁的.h文件中定義一個有參數(shù)無返回值的block
typedef void (^MyBox)(NSString *str);
2.在第三頁的.h文件中聲明一個block屬性
@property(nonatomic, copy)MyBox box;
3.在第三頁.m文件返回上一頁的按鈕點擊方法中將要傳的值進(jìn)行裝箱操作
- (void)didClickedButton:(UIButton *)button
{
self.box(self.textField.text);
[self.navigationController popViewControllerAnimated:YES];
}
4.在前一頁的.m文件跳轉(zhuǎn)到第三頁的按鈕點擊方法中給block一個實現(xiàn)體
- (void)didClickedButton:(UIButton *)button
{
ThreeViewController *tvc = [ThreeViewController new];
tvc.box = ^(NSString *str){
self.textField.text = str;
};
[self.navigationController pushViewController:tvc animated:YES];
}
點擊按鈕返回到第二頁的時候
3.通知中心
新建工程妒峦,創(chuàng)建兩個vc和相應(yīng)的label
1.在第二頁的.m文件中創(chuàng)建通知中心
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
//創(chuàng)建通知中心:
//通知中心發(fā)通知:
//參數(shù)1:通知中心的名字
//參數(shù)2:需要發(fā)送的內(nèi)容,接收者會得到這個對象
[[NSNotificationCenter defaultCenter] postNotificationName:@"整" object:self.label.text];
[self dismissViewControllerAnimated:YES completion:^{
nil;
}];
}
2.在第一頁.m文件中為當(dāng)前視圖添加通知中心
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(labelNotificationAction:) name:@"整" object:nil];
3.通知中心觸發(fā)的方法
- (void)labelNotificationAction:(NSNotification *)labelNotification
{
self.label.text = labelNotification.object;
}
頁面用模態(tài)方法跳轉(zhuǎn),也可在按鈕點擊方法里push
模態(tài)://模態(tài)過去時候的方法
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
SecondViewController *svc = [SecondViewController new];
[self presentViewController:svc animated:YES completion:^{
nil;
}];
}
在第二頁點擊屏幕時熬荆,模態(tài)到第一頁并把label的文字傳給第一頁的label