手機 APP 運行,不同頁面間傳值是必不可少,傳值的方式有很多(方法傳值,屬性傳值,代理傳值,單例傳值) ,這里主要總結(jié)下屬性傳值和代理傳值.
屬性傳值:屬性傳值是最簡單,也是最常見的一種傳值方式,但其具有局限性(一般用于將第一個頁面的值傳遞到第二個頁面,但無法從第二個頁面?zhèn)鞯降谝粋€頁面),
向SecondViewController傳值:SecondViewController 設(shè)置屬性 sendMessage
1 - (void)rightButtonAction:(UIBarButtonItem *)sender{2 SecondViewController *secondVC = [[SecondViewController alloc]init];3 secondVC.sendMessage = self.rootView.textField.text;4 [self.navigationController pushViewController:secondVC animated:YES];5 }
代理傳值:較難,不易理解,通常用于在第二個頁面向第一個頁面?zhèn)髦?一般分為六步
(例子采用 navigationController 跳轉(zhuǎn)頁面)
1.聲明協(xié)議 (寫在第二個頁面)
@PRotocol myDelegete <NSObject>- (void)sendMessage:(NSString*)message;@end
2.定義遵守協(xié)議的屬性 (寫在第二個頁面) (屬性必須用 assign )
@property (nonatomic , assign)id<myDelegete> delegate;
3.遵守協(xié)議(寫在第一個頁面)
1 @interface RootViewController : UIViewController <myDelegete>
4.設(shè)置代理 (設(shè)置代理寫在跳轉(zhuǎn)事件內(nèi)) (寫在第一個頁面)
1 - (void)rightButtonAction:(UIBarButtonItem *)sender{2 SecondViewController *secondVC = [[SecondViewController alloc]init];3 secondVC.sendMessage = self.rootView.textField.text;4 [self.navigationController pushViewController:secondVC animated:YES];5 //代理傳值第四步6 secondVC.delegate = self;7 8 }
5.實現(xiàn)協(xié)議方法 (寫在第一個頁面)
1 - (void)sendMessage:(NSString *)message{2 self.rootView.textField.text = message;3 }
6.實現(xiàn)傳值 (寫在第二個頁面)
1 - (void)leftButtonAction:(UIBarButtonItem *)sender{2 [self.navigationController popViewControllerAnimated:YES];3 //代理傳值第六步:4 [self.delegate sendMessage:self.secondView.textField.text];5 }
新聞熱點
疑難解答