
UIButtonはUIViewクラスのサブクラスなので、UIViewにaddSubviewして組み込む。
さっそくサンプルです~
@interface ButtonSampleView: UIView{
UIButton* btn1;
UIButton* btn2;
UIButton* btn3;
}
@end
@implementation ButtonSampleView
- (id)init{
self = [super init];
self.backgroundColor = [UIColor whiteColor];
btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn1 setTitle:@"RED" forState:UIControlStateNormal];
[btn1 addTarget:self action:@selector(btnTouch:) forControlEvents:UIControlEventTouchUpInside];
btn1.frame = CGRectMake(100, 40, 120, 30);
[self addSubview:btn1];
btn2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn2 setTitle:@"BLUE" forState:UIControlStateNormal];
[btn2 addTarget:self action:@selector(btnTouch:) forControlEvents:UIControlEventTouchUpInside];
btn2.frame = CGRectMake(100, 90, 120, 30);
[self addSubview:btn2];
btn3 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[btn3 setTitle:@"CLEAR" forState:UIControlStateNormal];
[btn3 addTarget:self action:@selector(btnTouch:) forControlEvents:UIControlEventTouchUpInside];
btn3.frame = CGRectMake(100, 140, 120, 30);
[self addSubview:btn3];
return self;
}
- (void)btnTouch:(UIButton*)btn{
if (btn == btn1){
self.backgroundColor = [UIColor redColor];
}
if (btn == btn2){
self.backgroundColor = [UIColor blueColor];
}
if (btn == btn3){
self.backgroundColor = [UIColor whiteColor];
}
}
@end
ボタンを3つ置いて背景色を変えるプログラム。
一番上は赤、真ん中は青、一番下は白に戻す。
いろいろタイプがあるけど、普通のカドのまるいボタンはUIButtonTypeRoundedRect。
これを使います

[btn1 setTitle:@"RED" forState:UIControlStateNormal];
でボタンのラベル設定する。forStateの設定で、ボタンの状態ごとにラベルを変えることもできる。
[btn3 addTarget:self action:@selector(btnTouch:) forControlEvents:UIControlEventTouchUpInside];
で、ボタンを押したとき(ボタンから指をはなしたとき)に、クラス自身のbtnTouch:メソッドが実行されるように設定。
ダイレクトにボタンを押したタイミングで実行させたいときはイベントをUIControlEventTouchDownにする。
これでクラスができた~!なので、組み込みまする。
UIView* oya = [[UIView alloc]init];
oya.frame = CGRectMake(0, 0, 320, 480);
ButtonSampleView* view = [[ButtonSampleView alloc]init];
view.frame = CGRectMake(0, 0, 320, 480);
[oya addSubview:view];
できました~!
ではでは。
画面ショット載せときます。





