2013年1月20日日曜日

007-Button(UIButton)

今回もstroyboardを使わないシリーズです。

ラベル作成が簡単だったので、
今回も簡単だと思っています。おそらく余裕ですね。

代表的なユーザー操作である、
ボタンを押すという処理。

ボタンを制する物はユーザーを制するとかしないとか。

//ボタンの生成・ボタンタイプの指定
UIButton *oButton =[UIButton buttonWithType:UIButtonTypeRoundedRect];
//ボタン枠の作成
oButton.frame = CGRectMake(00.0f, 150.0f, 300.0f, 50.0f);
//普段のボタンタイトル
[oButton setTitle:@"Hello World" forState:UIControlStateNormal];
//ボタン押下時のタイトル
[oButton setTitle:@"Goodbye World!!" forState:UIControlStateHighlighted];
// ボタンがタッチダウンされた時にonPushメソッドを呼び出す
[oButton addTarget:self action:@selector(onPush::)forControlEvents:UIControlEventTouchDown];
//ボタンを画面に追加
[self.view addSubview:oButton];


こんな感じで。。
ラベルと違って、
buttonTypeを指定しないと画面に表示されませんでした。。。

[oButton addTarget:self action:@selector(onPush::)forControlEvents:UIControlEventTouchDown];
ボタン押下時にonPushという関数を読んでいます。


呼ばれる関数はこんな感じで作っちゃってください。
-(void)onPush:(UIButton*)button:(id)sender{

}

Androidのように
クッリクした時の処理を別関数で作る仕様になっております。

また、idを引数にする事で、オブジェクトをなんでも渡せます。
なので、割と便利。。




■サンプルソース
h.ファイル

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{
    UILabel *oLabel;
}

@end



m.ファイル
#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    //ボタンの生成・ボタンタイプの指定
    UIButton *oButton =[UIButton buttonWithType:UIButtonTypeRoundedRect];
    //ボタン枠の作成
    oButton.frame = CGRectMake(00.0f, 150.0f, 300.0f, 50.0f);
    //普段のボタンタイトル
    [oButton setTitle:@"Hello World" forState:UIControlStateNormal];
    //ボタン押下時のタイトル
    [oButton setTitle:@"Goodbye World!!" forState:UIControlStateHighlighted];
    // ボタンがタッチダウンされた時にhogeメソッドを呼び出す
    [oButton addTarget:self action:@selector(onPush::)forControlEvents:UIControlEventTouchDown];
    //ボタンを画面に追加
    [self.view addSubview:oButton];
    
    //順位を表示するラベル
    oLabel = [[UILabel alloc] init];
    //枠の作成
    oLabel.frame = CGRectMake(00.0f, 00.0f, 350.0f, 100.0f);
    //文字列をラベルに設定
    oLabel.text = @"ボタン押された";
    //背景色をかえる
    oLabel.backgroundColor = [UIColor blackColor];
    //文字の色
    oLabel.textColor = [UIColor yellowColor];
    //フォントの設定
    oLabel.font = [UIFont fontWithName:@"AppleGothic" size:24];
    //文字の場所
    oLabel.textAlignment = UITextAlignmentCenter;
    [oLabel setHidden:YES];

    //Viewに追加
   [self.view addSubview:oLabel];
    
    [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

// 呼ばれるhogeメソッド
-(void)onPush:(UIButton*)button:(id)sender{
    Boolean bPushFlg = [oLabel isHidden];
    [oLabel setHidden:!bPushFlg];
}
@end


■実行結果
1.初期起動時

2,ボタン押下後
3.もう一回ボタンを押すと

こんな感じになります。

ボタンを押すと前回紹介したラベルを表示させます。


Boolean bPushFlg = [oLabel isHidden];
[oLabel setHidden:!bPushFlg];


Hiddenを使う事で、
表示、非表示の設定をしています。

取得した現在のステータスの反対を
設定しています。

0 件のコメント:

コメントを投稿