LoginSignup
3
4

More than 5 years have passed since last update.

[iOS][Objective-C] StoryBoardを使ったUI実装

Posted at

流れ

  1. MainStoryboard.storyboardに右下ペインから任意のUIパーツを選択、ドラッグで設置。

  2. UIパーツをViewController.hの@interface~@endの間にドラッグ。
     →設定ダイアログがポップアップされるので、任意値を設定。

  3. この時点で、ViewController.mに設置したActionの定義が自動追記されているので、
    メソッドの中身を追記していく。

Sample

以下機能を持つサンプルをつくる。
・ボタンを押すとアラートダイアログが表示される
・ダイアログ内での選択に応じて表示文字列を変化させる。

  1. MainStoryboard.storyboardにLabelとRoundRectButtonを設置

  2. LabelとRoundRectButtonをViewController.hの@interface~@endの間にドラッグ。
    設定ダイアログ内での値は

Connection:Outlet
Object:ViewController
Name:labelForAlertView
Type:UILabel
Storage:Weak
Connection:Action
Object:ViewController
Name:showAlertView
Type:id
Event:TouchUpInside
Arguments:None

※Connection
 Buttonなどイベントを設置するものはAction
  →メソッドとしてViewControllerに定義が自動追記される。
 特にイベント発火しないlabelなどのリソースはOutlet
  →propertyとしてViewControllerに定義が自動追記される。

するとViewController.h上に

@property (weak, nonatomic) IBOutlet UILabel *labelForAlertView

 - (IBAction)showAlertView;

の二つが自動生成される

  1. ViewController.mに以下メソッドが自動追記されているので、
 - (IBAction)showAlertView {   
}

メソッドの中身を実装。

 - (IBAction)showAlertView {

        UIAlertView *alertView = [
            [UIAlertView alloc] initWithTitle:@"たいとる" 
            message:@"本文" 
            delegate:nil 
            cancelButtonTitle:nil 
            otherButtonTitles:@"OK", nil
        ];
        [alertView show];
}

これで、RoundRectButtonをタップすると、alertViewが表示される。

さらに、alertView内でのアクションを拾うメソッドを追記する。

- (void)alertView:(UIAlertView *)alertView
        clickedButtonAtIndex:(NSInteger)buttonIndex
{
        if(buttonIndex == 0){
            self.labelForAlertView.text = @"canceled";
        } else if (buttonIndex == 1) {
            self.labelForAlertView.text = @"ok is pushed";
        }
}

buttonIndexは、alertView内でキャンセル選択で0、OK選択で1を返す。
ここではそれにあわせてlabelForAlertViewの値を書き換えている。

参考

iPhoneアプリ開発超入門
http://www.sbcr.jp/products/4797369434.html

3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4