Deca-pod.jp

Anything

UIButtonを使って画面遷移をする。

まずボタンを作成する。

//ボタンが押されるとpushAlertメソッドを呼び出す。
    SEL method = @selector(pushAlert);
    UIButton * button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    button.frame = CGRectMake(20, 20, 40, 15);
    [button setTitle:@"btn" forState:UIControlStateNormal];
    [button addTarget:self action:method forControlEvents:UIControlEventTouchUpInside];
    
   
    [self.view addSubview:button];

実行するとこんな感じ。
f:id:vaikong:20140911004031p:plain

タップするとアラートが出るようにする。
UIAlertViewDelegateをプロトコルに設定して。

#import <UIKit/UIKit.h>
#import "ViewController2.h"
@interface ViewController : UIViewController <UIAlertViewDelegate>

@end

アラートを設定する。

-(void)pushAlert{
    UIAlertView * alert = [[UIAlertView alloc]initWithTitle:@"画面遷移しますか?"message:nil delegate:self cancelButtonTitle:@"no" otherButtonTitles:@"ok", nil];
    [alert show];
}

表示してみる。
f:id:vaikong:20140911004451p:plain

UIAlertViewのalertViewメソッドをオーバーライドしてアラートでokが選択されたら画面を遷移するようにする。

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    
    ViewController2 * vc2 = [self.storyboard instantiateViewControllerWithIdentifier:@"VC2"];
//トランジションをクロスディゾルブに変更
    vc2.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
   
    switch (buttonIndex) {
        case 0:
            
            break;
        case 1:
            [self presentViewController:vc2 animated:YES completion:nil];
           
            break;
        default:
            break;
    }
}

第二引数のbuttonIndexが各々のtitleに対応している。
(0がキャンセル、1がotherButtonTitleです。)

okボタンを押すと・・
f:id:vaikong:20140911005121p:plain

無事画面遷移に成功しました。