iPhone/iPadのネイティブアプリでフォームっぽいUIを使いたくなることが多いのですが、UIKitにはなぜかラジオボタンがなくていっつも困るので簡単なラジオボタンを実装してみました。

サンプルのプロジェクトをgithubにあげときました。
- Githubページ : t4ku / RadioButtonWithUIKit
- Zipダウンロード : Download
RadioButtonViewController.m
グループIDとグループ内での番号を指定してラジオボックスのUIを初期化します。
RadioButton *rb1 = [[RadioButton alloc] initWithGroupId:@"first group" index:0];
RadioButton *rb2 = [[RadioButton alloc] initWithGroupId:@"first group" index:1];
RadioButton *rb3 = [[RadioButton alloc] initWithGroupId:@"first group" index:2];
rb1.frame = CGRectMake(10,30,22,22);
rb2.frame = CGRectMake(10,60,22,22);
rb3.frame = CGRectMake(10,90,22,22);
[self.view addSubview:rb1];
[self.view addSubview:rb2];
[self.view addSubview:rb3];
// 選択値が変わったときに、delegateメソッドが呼ばれるようにする
[RadioButton addObserverForGroupId:@"first group" observer:self];
RadioButton *rb2 = [[RadioButton alloc] initWithGroupId:@"first group" index:1];
RadioButton *rb3 = [[RadioButton alloc] initWithGroupId:@"first group" index:2];
rb1.frame = CGRectMake(10,30,22,22);
rb2.frame = CGRectMake(10,60,22,22);
rb3.frame = CGRectMake(10,90,22,22);
[self.view addSubview:rb1];
[self.view addSubview:rb2];
[self.view addSubview:rb3];
// 選択値が変わったときに、delegateメソッドが呼ばれるようにする
[RadioButton addObserverForGroupId:@"first group" observer:self];
RadioButton.h
ラジオボタンの選択状態が変わったときに呼ばれるdelegateメソッドの宣言は下記。
@protocol RadioButtonDelegate <NSObject>
-(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString*)groupId;
@end
-(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString*)groupId;
@end
RadioButtonViewController.m
実装例。単にグループIDとグループ内の何番目のラジオボタンが押されたかを表示
-(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString *)groupId{
NSLog(@"changed to %d in %@",index,groupId);
}
NSLog(@"changed to %d in %@",index,groupId);
}
実装してみて思ったのは、今回はRadioButtonというUIViewのサブクラスに全部いれこんだんですが、ホントはラジオボタン間のやりとりを別クラス(RadioButtonGroupとか)にしといたほうがよいかもとか、ラベルとかも一緒に(textViewとかプロパティつくって)管理したほうがよいかもとか。。。まあ、Quick&Dirtyで行きましょう。
193 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.
Continuing the Discussion