ModalViewのお話(2) | 初心者がiPhoneアプリを作るブログ

初心者がiPhoneアプリを作るブログ

初心者がiPhoneアプリを作るブログです.
入門レベルですので開発初心者にも,できるだけ分かるように丁寧に説明していきます(多分).

今回は,
はじめに表示するUIViewController:「CustomViewController」と
モーダルビューとして表示するUIViewController:「ModalViewController」の
2つのクラスを作成していきます.

それではまずCustomViewControllerから.
こちらは,ボタンを押したら,モーダルビューがでてくるように作成していきます.
CustomViewController.m
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    [self.view setBackgroundColor:[UIColor colorWithRed:0.0 green:0.5 blue:1.0 alpha:0.1]];
    
    CGFloat frameWidth = self.view.frame.size.width;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeInfoLight];
    [button setFrame:CGRectMake(frameWidth - 50, 10, 40, 40)];
    [button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchDown];
    
    [self.view addSubview:button];
}
// ボタンを押した時の関数を追記します
- (void)buttonTouched:(UIButton *)button{
    // モーダルビューを作成
    ModalViewController *modalView = [[ModalViewController alloc] initWithNibName:nil bundle:nil];

    // アニメーション開始
    [self presentModalViewController:modalView animated:YES];
}

ファイルのどこかに,上記の関数「- (void)viewDIdLoad」がコメントアウトされていると思いますので探して下さい.
見つけたら,コメントを解除して下さいね.

この関数は,ViewControllerが管理するViewにアクセスが開始されると呼ばれます.
viewDidLoadが呼ばれるタイミングについては別の機会でお話します.

要は,UIViewControllerが管理するViewについて編集したければ,
ViewDidLoad内に書けば問題ない!!

ということです.

ちなみにviewDidLoad内ではボタンを作って配置しただけです.
次はその処理について見ていきましょう.

// ボタンを押した時の関数を追記します
- (void)buttonTouched:(UIButton *)button{
    // モーダルビューを作成

    ModalViewController *modalView = [[ModalViewController alloc] initWithNibName:nil bundle:nil];
    // アニメーション開始
    [self presentModalViewController:modalView animated:YES];
}


ModalViewControllerという怪しいクラスがありますが,
つまりは,UIViewControllerのサブクラス(継承したクラス)です.
そのインスタンスを作成しています.

,そのインスタンスを2行目の関数を使ってあげることで,
ビューが画面下から上がってくる訳ですね.

とっても簡単ですね!!
では,次の記事では,謎クラスのModalViewControllerについて見ましょう.

次の記事へ

HOMEに戻る