iOS 頁面間傳值 之 屬性傳值,代理傳值,ios頁面

來源:互聯網
上載者:User

iOS 頁面間傳值 之 屬性傳值,代理傳值,ios頁面

手機 APP 運行,不同頁面間傳值是必不可少,傳值的方式有很多(方法傳值,屬性傳值,代理傳值,單例傳值) ,這裡主要總結下屬性傳值和代理傳值.

屬性傳值:屬性傳值是最簡單,也是最常見的一種傳值方式,但其具有局限性(一般用於將第一個頁面的值傳遞到第二個頁面,但無法從第二個頁面傳到第一個頁面),

  向SecondViewController傳值:SecondViewController 設定屬性 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 }

 

代理傳值:較難,不易理解,通常用於在第二個頁面向第一個頁面傳值.一般分為六步

(例子採用 navigationController 跳轉頁面)

1.聲明協議 (寫在第二個頁面)

@protocol myDelegete <NSObject>- (void)sendMessage:(NSString*)message;@end

 

2.定義遵守協議的屬性 (寫在第二個頁面) (屬性必須用 assign )

@property (nonatomic , assign)id<myDelegete> delegate;

 

3.遵守協議(寫在第一個頁面)

1 @interface RootViewController : UIViewController <myDelegete>

 

4.設定代理 (設定代理寫在跳轉事件內) (寫在第一個頁面)

 

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.實現協議方法 (寫在第一個頁面)

 

1 - (void)sendMessage:(NSString *)message{2     self.rootView.textField.text = message;3 }

 

 

 

6.實現傳值 (寫在第二個頁面)

1 - (void)leftButtonAction:(UIBarButtonItem *)sender{2     [self.navigationController popViewControllerAnimated:YES];3     //代理傳值第六步:4     [self.delegate sendMessage:self.secondView.textField.text];5 }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.