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

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

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

今回は,UIAlertViewについて説明します.
UIAlertViewとは,

UIAlertView_sample
こんなやつです.
結構簡単にできます.

さっそくサンプルプログラムを書いてみましょう.
作るプログラムは,
UIViewの上にUIButtonがあり,そのボタンを押すと,画像のように
UIAlertViewが出てくるようにしましょう.

とりあえず,UIViewControllerを継承したCustomViewControllerを作成しましょう.
ではCustomViewControllerの一部を載せますね.
CustomViewController.m

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor colorWithRed:0.5 green:1.0 blue:0.0 alpha:0.1]];
    
    CGFloat frameWidth = self.view.frame.size.width;
    CGFloat frameHeight = self.view.frame.size.height;
    UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setFrame:CGRectMake(frameWidth / 2 - 50, frameHeight / 2 - 25, 100, 50)];
    [button setTitle:@"OK" forState:UIControlStateNormal];
    [button addTarget:self action:@selector(buttonTouched:) forControlEvents:UIControlEventTouchDown];
    
    [self.view addSubview:button];
}


- (void)buttonTouched:(UIButton *)button{
    // UIAlertViewの初期化
    UIAlertView *alert = [[UIAlertView alloc
                          initWithTitle:@"Touched!!"
                          message:@"Button is Touched!!"
                          delegate:nil
                          cancelButtonTitle:@"Cancel"
                          otherButtonTitles:@"OK", nil];
    // UIAlertViewを表示する
    [alert show];
}


さて,viewDidLoadの中身はいいでしょう.
ボタンを押した時の処理について見てみましょう.
まず,UIAlertViewを初期化します.
それを表示します.
終わりです.
簡単です.

もう少し詳しく初期化メソッドを見ましょう.
initWithTitle:alertViewのタイトルを設定します
message:alertViewで表示するメッセージを設定します.これは複数行設定可能です.(ヒント:「\n」)
delegate:とりあえずここは「nil」にしといて下さい.
cancelButtonTitle:押したら何もせずにUIAlertViewが消えるボタンのタイトルを設定します.(だいたいOKとかキャンセルとか)
otherButtonTitles:その他のボタンを設定します.複数個設定可能です.後で詳しく見ましょう.

こんなとこですかね.
実行してみましょう!!無事表示されましたか??

先程,ボタンは複数個設定可能と書きましたが,複数個設定したい場合は
UIAlertView *alert = [[UIAlertView alloc] 
                      initWithTitle:@"Touched!!"
                      message:@"Button is Touched!!"
                      delegate:nil
                      cancelButtonTitle:@"Cancel
                      otherButtonTitles:@"OK", @"OK1", @"OK2", nil];

このようにコンマで区切って複数文字列を指定すればOKです.

さて.実行した人はお気付きでしょう.
OKボタン押しても結局キャンセルと同じ動きしてんじゃん!!!

そうなんです.なぜなら処理を設定していませんからね笑

この後の処理をするために「delegate」を使います.それを次のエントリで説明しましょう.

次の記事へ

HOMEに戻る