// UIButtonを作成
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 位置,サイズを設定
button.frame = CGRectMake(frame.size.width / 2 - 50, frame.size.height / 2 - 25, 100, 50);
// ボタンに表示する名前を設定
[button setTitle:@"touch" forState:UIControlStateNormal];
// ボタンを押した際の処理をする関数を設定
[button addTarget:self action:@selector(buttonTouch:) forControlEvents:UIControlEventTouchDown];
// ボタンを配置
[firstViewController.view addSubview:button];
UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
// 位置,サイズを設定
button.frame = CGRectMake(frame.size.width / 2 - 50, frame.size.height / 2 - 25, 100, 50);
// ボタンに表示する名前を設定
[button setTitle:@"touch" forState:UIControlStateNormal];
// ボタンを押した際の処理をする関数を設定
[button addTarget:self action:@selector(buttonTouch:) forControlEvents:UIControlEventTouchDown];
// ボタンを配置
[firstViewController.view addSubview:button];
押すと画面が遷移するボタンを作成します.
ここで作成しているUIButtonはUIViewのサブクラス,つまり,UIViewを継承しています.
まず,UIButtonのインスタンスを作成します.
その後,ボタンの位置,サイズを指定します.
これは,UIViewのプロパティである「frame」を設定することで可能です.
frameはCGRect型ですので,CGRectMake()という関数を使います.
次に,ボタンに表示する文字列を設定しています.
そして,ボタンを押した際の処理をする関数を設定しています.
[button addTarget:self action:@selector(buttonTouch:) forControlEvents:UIControlEventTouchDown];
「addTarget」で処理を行う関数が書かれているインスタンスを指定し,
「action」で関数名を指定 (@selector("関数名":))
「forControlEvents」でボタンにどのようなイベントが起きた場合に関数を呼び出すかを指定
します!!!
この説明であってるはず!!笑
最後にviewに配置します.
次に,ボタンが押された時の処理について書いていきます.
- (void)buttonTouch:(UIButton *)button{
// 遷移した先のUIViewControllerを作成
UIViewController *nextViewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
nextViewController.view.backgroundColor = [UIColor greenColor];
nextViewController.title = [NSString stringWithString:@"next"];
// ここで遷移します
[navigationController pushViewController:nextViewController animated:YES];
}
// 遷移した先のUIViewControllerを作成
UIViewController *nextViewController = [[UIViewController alloc] initWithNibName:nil bundle:nil];
nextViewController.view.backgroundColor = [UIColor greenColor];
nextViewController.title = [NSString stringWithString:@"next"];
// ここで遷移します
[navigationController pushViewController:nextViewController animated:YES];
}
関数名は先程設定した関数名にし,引数を「(UIButton *)button」にします.
型をUIButton *にしていれば,変数名はbuttonではなくてもいいと思います.
先程@selector(buttonTouch:)と設定しました.
「:」があるので,ボタンが押された時に,そのボタン自身を引数として渡しているみたいです.
さて,ややこしくなって参りましたが,ボタンが押された時の処理について見ていきます.
ボタンが押されたら,画面が遷移して欲しいので,遷移先のUIView,UIViewControllerを作成します.
その後,いよいよ遷移をするのですが,
[navigationController pushViewController:nextViewController animated:YES];
UINavigationControllerのpushViewControllerという関数を使います.引数は次に表示するviewControllerです.更にanimatedをYESにすると,遷移する際にアニメーションで遷移します.
これをNOにすると,一瞬で画面が切り替わって面白くないです笑
というのは冗談で,場合によって使い分けて下さいね.
以上で一通り解説が終わりました.
やっぱUINavigationControllerは難しいです.
実行してみましょう.
TouchButtonを押すと,赤い画面から,緑の画面に遷移しましたか?
ナビゲーションバーのタイトルは変わりましたか?
緑の画面から赤い画面に戻れましたか?
これがUINavigationControllerです.
難しいけど,いろいろ試しながら覚えて下さいね.
次の記事へ
HOMEに戻る