IOS開發之頁面間傳值的幾種小方法,ios頁面

來源:互聯網
上載者:User

IOS開發之頁面間傳值的幾種小方法,ios頁面

最正經的頁面間傳值方式莫過於代理傳值,今天寫的幾種小方法不包括代理傳值,因為是自學的原因,現在都不知道這幾種方法的優缺點,往知道的朋友指正一下;

 

第一種:屬性傳值;(這種方法在故事版無效,適合純程式碼編寫時使用,為什嗎???)

    前提:比如說有兩個視圖控制器:AViewController和BViewController,他們之間想從A傳值到B,

    ——》在AViewController.m檔案中

           (1)匯入BViewController

           #import "BViewController.h"

           (2)定義全域變數

           比如:我們在A中加一個UITextfield控制項,將他的值傳遞到B

@property (nonatomic, strong) UITextField *text;

 

 

           (3)需要傳值的地方編碼

    BViewController *Bvc = [[BViewController alloc] initWithNibName:nil bundle:nil];    //賦值    Bvc.chuanzhi = text.text;    //跳轉    [self.navigationController pushViewController:Bvc animated:YES];

 

 

         ——》在BVIewController.h檔案中

          定義上一步編碼時,賦值時Bvc.chuanzhi 的變數就是我們需要在.h檔案中定義的;

@property (nonatomic, strong) NSString *chuanzhi;

 

     ——》在BViewController.m檔案中

          這樣我們就可以在B中隨處使用傳遞過來的值;

 

 

第二種:segue傳值;

前提:比如說有兩個視圖控制器:AViewController和BViewController,他們之間想從A傳值到B,它們之間的連線Identifier:aTob

 

  ——》AViewController.m檔案中

     (1)開啟下面這個方法

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

   

    (2)在其中進行傳值

       

// In a storyboard-based application, you will often want to do a little preparation before navigation- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {        if([segue.identifier isEqualToString:@"aTob"])    {        id theSegue = segue.destinationViewController;        //賦值        [theSegue setValue:@"A頁面的值" forKey:@"自己的KEY"];    }}

    

     ——》在BviewController中的操作和上一種方法一樣

 

 第三種:用NSUserDefaults傳值;

 

       ——》AViewController中

      需要傳值的地方編碼

    //儲存資料    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    [defaults setObject:@"A介面需要傳遞的值" forKey:@"自己的KEY"];    //設定同步    [defaults synchronize];

 

      ——》BViewController檔案中

        在ViewDidLoad中編碼讀取傳遞過來的值

 

    //讀取A介面傳遞過來的值    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];    self.userId = [defaults valueForKey:@"自己的KEY"];

 

 

       

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.