iOS頁面傳值總結

  1. 從最簡單的頁面跳轉開始提及, FirstViewController -----> SecondViewControlleratom

方法:直接在跳轉處直接給第二個控制器的屬性賦值spa

// FirstViewController.m
// ...
SecondViewController *sec = [SecondViewController new];
sec.backgroundColor = [UIColor RedColor];   // 直接給SecondViewController屬性賦值
sec.delegate = self;                        // 第二種情形使用
[self.navigationController pushViewController:sec animation:YES completion:nil];   // 跳轉
// ...

2.   比上面稍微複雜的跳轉 ,  FirstViewController -------> SecondViewController -------->FirstViewController.net

實現功能:FirstViewController 經過某個動做(好比點擊按鈕) push到SecondViewController中,當SecondViewController 返回的時候,在FirstViewController上的label上顯示從SecondViewController中傳過來的一個字符串(@「info」)代理

 方法1:經過委託delegate的方法實現  (委託方、代理方、協議)code

// SecondViewController.h

// step 1 : 建立一個代理(delegate)
@protocol secondViewDelegate
- (void)showInfo:(NSString *)info;
@end 


@interfacr SecondViewController : UIViewController

// step 2 : (委託方)聲明一個代理
@property (nonatomic , weak) id<secondViewDelegate>delegate;  // weak 是亮點,是爲了防止循環引用
@end
// SecondViewController.m

- (void)viewWillBackToFirstView{

// step 3 : (委託方)調用delegate方法
    [_delegate showInfo:@"info"];
    [self.navigationController popViewController];
}
// FirstViewController.m

SecondViewController *sec = [SecondViewController new];

// step 4 : (代理方)設置delegate,以便被委託方調用
sec.delegate = self;                      
[self.navigationController pushViewController:sec animation:YES completion:nil]; 

// step 5 : (代理方)實現協議
- (void)showInfo:(NSString *)info{
    self.label.text = info;   // 把委託方傳過來的字符串顯示在界面上
}
  • 代理試用的3個主體:delegate、委託者、代理者blog

  • 代理使用的5個通常步驟字符串

  1. 【用@protocol...@end】            建立一個delegateget

  2. 【委託者用@property ~~】         聲明一個delegate屬性animation

  3. 【委託者用 [_delegate ~~] 】     調用delegate內的方法io

  4. 【代理者用 ~~.delegate = self】 設置delegate,以便委託者調用(步驟3)

  5. 【代理者】                                實現delegate方法

  •  總結:delegate實現了不一樣視圖之間的數據交互;delegate屬於時間驅動範疇,只有當某一時間觸發是,delegate才被調用

方法2:經過block方式實現

// SecondViewController
typedef void (^ablock)(NSString *str);

// step 1: 在SecondViewController中,聲明一個block屬性,參數爲字符串 <------>對比委託方聲明一個代理
@property (nonatomic,copy) ablock block;
// @property (nonatomic , weak) id<secondViewDelegate>delegate;

//  step 2: 在SecondViewController中,調用block <--------> 對比委託方調用delegate方法
self.block(@"info");
// [_delegate showInfo:@"info"];
// [self.navigationController popViewController];
// FirstViewController.h

// step 3: 在FirstViewController中,回掉block <----------> 對比代理方實現delegate方法
[self.navigationController pushViewController:sec animation:YES completion:nil];
sec.block = ^(NSString *info){
    self.label.text = info
     };
// sec.delegate = self;                      
// [self.navigationController pushViewController:sec animation:YES completion:nil];

關於block的講解:有一篇不錯的文章http://my.oschina.net/leejan97/blog/268536,講的很透徹

相關文章
相關標籤/搜索