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"];