本文為年夜家分享了IOS掌握器之間數據的雙向傳遞,供年夜家參考,詳細內容以下
起首,有兩個掌握器,分離為掌握器A、掌握器B。
A->B:數據由掌握器A傳向掌握器B,這叫做數據的順傳;數據由掌握器B傳向掌握器A,這叫做逆傳。
順傳:普通經由過程創立目的掌握器對象,將數據賦值給對象的成員來完成;
逆傳:普通應用署理來完成,個中掌握器A是掌握器B的署理(掌握器A監聽掌握器B,掌握器B告訴掌握器A)。
上面是博主寫的簡略完成了兩個掌握間完成數據的雙向傳遞的app的demo:
1、這是界面設計:

FirstViewController.h
#import <UIKit/UIKit.h> @interface FirstViewController : UIViewController @end
FirstViewController.m
#import "FirstViewController.h"
#import "SecondViewController.h"
@interface FirstViewController ()<SecondViewControllerDelegate>
/** 用於寫入數據,最初該數據用於傳遞給第二個界面 */
@property (weak, nonatomic) IBOutlet UITextField *first2Second;
/** 用於顯示第二個界面前往來時傳遞的數據 */
@property (weak, nonatomic) IBOutlet UITextField *displayWithSecond;
@end
@implementation FirstViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
#pragma mark - Navigation
//點擊傳遞按鈕時會主動挪用此辦法
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
SecondViewController *vc = (SecondViewController *)segue.destinationViewController;
if (self.first2Second.text.length > 0) {
//將該界面中的數據傳遞給第二個界面
vc.name = self.first2Second.text;
}
//設置以後掌握器為SecondViewController掌握器的署理
vc.delegate = self;
}
#pragma mark - 完成SecondViewControllerDelegate中的協定辦法
-(void)secondViewControllerDidDit:(SecondViewController *)viewController andName:(NSString *)name
{
//將第二個界面中的數據前往給第一個界面(此界面)
self.displayWithSecond.text = name;
}
@end
SecondViewController.h
#import <UIKit/UIKit.h> @class SecondViewController; @protocol SecondViewControllerDelegate <NSObject> /** SecondViewControllerDelegate協定中的辦法 */ -(void)secondViewControllerDidDit:(SecondViewController *)viewController andName:(NSString *)name; @end @interface SecondViewController : UIViewController @property(nonatomic,strong) NSString *name; @property(nonatomic,weak) id<SecondViewControllerDelegate> delegate; @end
SecondViewController.m
#import "SecondViewController.h"
@interface SecondViewController ()
/** 用於寫入數據,最初將數據前往給第一個界面 */
@property (weak, nonatomic) IBOutlet UITextField *second2First;
/** 用於顯示第一個界面傳過去的數據 */
@property (weak, nonatomic) IBOutlet UITextField *displayWithFirst;
/** 點擊此按鈕,第二個掌握器將彈出棧,界面將前往到第一個界面 */
- (IBAction)second2First:(UIButton *)sender;
@end
@implementation SecondViewController
- (void)viewDidLoad {
[super viewDidLoad];
//顯示第一個界面傳遞過去的數據信息
self.displayWithFirst.text = self.name;
}
//點擊該按鈕,數據將前往給第一個界面顯示
- (IBAction)second2First:(UIButton *)sender {
if (self.second2First.text.length > 0) {
//假如有完成該協定辦法的掌握器,則將數據傳給該掌握器
if ([self.delegate respondsToSelector:@selector(secondViewControllerDidDit:andName:)]) {
[self.delegate secondViewControllerDidDit:self andName:self.second2First.text];
}
}
[self.navigationController popViewControllerAnimated:YES];
}
@end
以上就是本文的全體內容,願望能給年夜家一個參考,也願望年夜家多多支撐本站。
【iOS完成兩個掌握器之間數據的雙向傳遞】的相關資料介紹到這裡,希望對您有所幫助! 提示:不會對讀者因本文所帶來的任何損失負責。如果您支持就請把本站添加至收藏夾哦!