ストーリーボードを連結し、パラメータを渡して画面遷移するサンプルを以下に作成しました。
サンプルダウンロード
必要な手順
- MainStoryBoardを開き、新しい UIViewControllerを画面に配置します
- controlキーを押しながら、最初の UIViewControllerから新しい UIViewControllerへ矢印をドラッグします
- UIViewController同士の間にできたアイコンを選択し、セグエの Identiferを指定します ※スクリーンショット1
- 新規ファイルから UIViewControllerのクラスを作成し、ここでは「SecondViewController」とします ※スクリーンショット2
- MainStoryBoard上から「SecondViewController」の下部分を選択し、「SecondViewController」を指定します
スクリーンショット1

スクリーンショット2

ソースコード
ViewController.h
1
2
3
4
5
6
7
8
9
10
11
12
13
| #import <UIKit/UIKit.h>
@interface ViewController : UIViewController {
//次の画面へ渡す引数
NSString *_arguments;
}
@property (nonatomic) NSString *arguments;
@property (weak, nonatomic) IBOutlet UIButton *nextButton;
- (IBAction)nextButtonEvent:(id)sender;
@end
|
ViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| #import "ViewController.h"
//ここで次の画面のヘッダファイルをインポートする
#import "SecondViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
//次の画面へ渡す引数をセット
_arguments = @"arguments";
}
- (IBAction)nextButtonEvent:(id)sender {
//次の画面へ遷移
[self performSegueWithIdentifier:@"secondSegue" sender:self];
}
//画面遷移時に呼ばれるメソッド
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
//2つ目の画面にパラメータを渡して遷移する
if ([segue.identifier isEqualToString:@"secondSegue"]) {
//ここでパラメータを渡す
SecondViewController *secondViewController = segue.destinationViewController;
secondViewController.arguments = _arguments;
}
}
@end
|
SecondViewController.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| #import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController {
//前の画面から受け取る引数
NSString *_arguments;
}
@property (nonatomic) NSString *arguments;
@property (weak, nonatomic) IBOutlet UILabel *argumentsLabel;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
- (IBAction)backButtonEvent:(id)sender;
@end
|
SecondViewController.m
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| #import "SecondViewController.h"
@interface SecondViewController ()
@end
@implementation SecondViewController
@synthesize arguments = _arguments;
- (void)viewDidLoad
{
[super viewDidLoad];
//ラベルに前の画面から受け取った引数を表示
self.argumentsLabel.text = _arguments;
}
- (IBAction)backButtonEvent:(id)sender {
//前の画面へ戻る
[self dismissViewControllerAnimated:YES completion:NULL];
}
@end
|
関連記事
お薦めの参考書
絶対に挫折しない iPhoneアプリ開発「超」入門 増補改訂第4版
Swiftについて知りたい開発者の方のみならず、プログラミング未経験者の方にも参考になる内容になっています。Swiftの基礎を一から丁寧に解説されており、この書籍があればネットで調べる手間をかなり省くことができると思います。