storyboardでデータの受け渡し | tototan

storyboardでデータの受け渡し

自作iPhoneアプリ一覧

このチュートリアルではstoryboadを使って親のビューコントロールでテキストフィールドに入力した文字列を子のビューコントロラーラベルへ表示します。






コード編集の詳細

【ViewController.h】

#import

@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UITextField *textField;

@end


【ViewController.m】
#import "ViewController.h"
#import "SecondViewController.h"

@implementation ViewController
@synthesize textField;

#pragma mark - View lifecycle

- (void)viewDidLoad
{
   [super viewDidLoad];

   textField.delegate = self;
// Do any additional setup after loading the view, typically from a nib.
}


//Returnキーをタップした時、キーボードを隠すデリゲートメソッド
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
   [self.textField resignFirstResponder];
  return YES;
}



//Switch Viewボタンをタップした時の処理
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
  if ([[segue identifier] isEqualToString:@"showText"]) {
  //showTextはStoryboardのsequeのIdentifier名

  SecondViewController *svc =[segue destinationViewController];
  //destinationViewControllerとはsequeの右側にあるViewControllerらしい
  svc.labelData = self.textField.text;
  }
}



【SecondViewController.h】

#import

@interface SecondViewController : UIViewController

@property (weak, nonatomic) IBOutlet UILabel *label;
@property (strong, nonatomic) NSString *labelData; //データを格納する変数

- (IBAction)goFirstView:(id)sender;

@end


【SecondViewController.m】

#import "SecondViewController.h"

@implementation SecondViewController

@synthesize labelData;
@synthesize label;


- (void)viewDidLoad
{
   [super viewDidLoad];
  label.text = labelData;
}

サンプルコードダウンロード