iOS 中单选按钮的使用[可以按步骤复制代码先看效果]

一、创建一个单选按钮的类

#import <UIKit/UIKit.h>

@protocol RadioButtonDelegate

-(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString*)groupId;

@end

@interface RadioButton : UIView {

NSString *_groupId;

NSUInteger _index;

UIButton *_button;

}

@property(nonatomic,retain)NSString *groupId;

@property(nonatomic,assign)NSUInteger index;

-(id)initWithGroupId:(NSString*)groupId index:(NSUInteger)index;

+(void)addObserverForGroupId:(NSString*)groupId observer:(id)observer;

// 可以设置默认选中项

- (void) setChecked:(BOOL)isChecked;

@end

二、。m实现文件

#import "RadioButton.h"

@interface RadioButton()

-(void)defaultInit;

-(void)otherButtonSelected:(id)sender;

-(void)handleButtonTap:(id)sender;

@end

@implementation RadioButton

@synthesize groupId=_groupId;

@synthesize index=_index;

static const NSUInteger kRadioButtonWidth=22;

static const NSUInteger kRadioButtonHeight=22;

static NSMutableArray *rb_instances=nil;

static NSMutableDictionary *rb_instancesDic=nil;  // 识别不同的组

static NSMutableDictionary *rb_observers=nil;

#pragma mark - Observer

+(void)addObserverForGroupId:(NSString*)groupId observer:(id)observer{

if(!rb_observers){

rb_observers = [[NSMutableDictionary alloc] init];

}

if ([groupId length] > 0 && observer) {

[rb_observers setObject:observer forKey:groupId];

// Make it weak reference

[observer release];

}

}

#pragma mark - Manage Instances

+(void)registerInstance:(RadioButton*)radioButton withGroupID:(NSString *)aGroupID{

if(!rb_instancesDic){

rb_instancesDic = [[NSMutableDictionary alloc] initWithCapacity:16];

}

if ([rb_instancesDic objectForKey:aGroupID]) {

[[rb_instancesDic objectForKey:aGroupID] addObject:radioButton];

[rb_instancesDic setObject:[rb_instancesDic objectForKey:aGroupID] forKey:aGroupID];

[radioButton release];

}else {

NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:16];

[arr addObject:radioButton];

[radioButton release];

[rb_instancesDic setObject:arr forKey:aGroupID];

}

}

#pragma mark - Class level handler

+(void)buttonSelected:(RadioButton*)radioButton{

// Notify observers

if (rb_observers) {

id observer= [rb_observers objectForKey:radioButton.groupId];

if(observer && [observer respondsToSelector:@selector(radioButtonSelectedAtIndex:inGroup:)]){

[observer radioButtonSelectedAtIndex:radioButton.index inGroup:radioButton.groupId];

}

}

// Unselect the other radio buttons

// 初始化按钮数组

rb_instances = [rb_instancesDic objectForKey:radioButton.groupId];

if (rb_instances) {

for (int i = 0; i < [rb_instances count]; i++) {

RadioButton *button = [rb_instances objectAtIndex:i];

if (![button isEqual:radioButton]) {

[button otherButtonSelected:radioButton];

}

}

}

}

#pragma mark - Object Lifecycle

-(id)initWithGroupId:(NSString*)groupId index:(NSUInteger)index{

self = [self init];

if (self) {

_groupId = groupId;

_index = index;

[self defaultInit];  // 移动至此

}

return  self;

}

- (id)init{

self = [super init];

if (self) {

//      [self defaultInit];

}

return self;

}

- (void)dealloc

{

[_groupId release];

[_button release];

[super dealloc];

}

#pragma mark - Set Default Checked

- (void) setChecked:(BOOL)isChecked

{

if (isChecked) {

[_button setSelected:YES];

}else {

[_button setSelected:NO];

}

}

#pragma mark - Tap handling

-(void)handleButtonTap:(id)sender{

[_button setSelected:YES];

[RadioButton buttonSelected:self];

}

-(void)otherButtonSelected:(id)sender{

// Called when other radio button instance got selected

if(_button.selected){

[_button setSelected:NO];

}

}

#pragma mark - RadioButton init

-(void)defaultInit{

// Setup container view

self.frame = CGRectMake(0, 0, kRadioButtonWidth, kRadioButtonHeight);

// Customize UIButton

_button = [UIButton buttonWithType:UIButtonTypeCustom];

_button.frame = CGRectMake(0, 0,kRadioButtonWidth, kRadioButtonHeight);

_button.adjustsImageWhenHighlighted = NO;

[_button setImage:[UIImage imageNamed:@"RadioButton-Unselected"] forState:UIControlStateNormal];

[_button setImage:[UIImage imageNamed:@"RadioButton-Selected"] forState:UIControlStateSelected];

[_button addTarget:self action:@selector(handleButtonTap:) forControlEvents:UIControlEventTouchUpInside];

[self addSubview:_button];

//  [RadioButton registerInstance:self];

// update follow:

[RadioButton registerInstance:self withGroupID:self.groupId];

}

@end

三、使用

在控制器的。m文件中

#import "RadioButton.h"

@interface RadioButtonViewController()<RadioButtonDelegate>

@property (nonatomic,retain) NSMutableDictionary *dic;

@end

@implementation RadioButtonViewController

@synthesize dic=_dic;

- (void)viewDidLoad

{

[super viewDidLoad];

UIView *container = [[UIView alloc] initWithFrame:CGRectMake(10, 20, 300, 400)];

container.backgroundColor = [UIColor lightGrayColor];

[self.view addSubview:container];

UILabel *questionText = [[UILabel alloc] initWithFrame:CGRectMake(0,0,280,20)];

questionText.backgroundColor = [UIColor clearColor];

questionText.text = @"1. Which color do you like?";

[container addSubview:questionText];

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);

[container addSubview:rb1];

[container addSubview:rb2];

[container addSubview:rb3];

UILabel *label1 =[[UILabel alloc] initWithFrame:CGRectMake(40, 30, 60, 20)];

label1.backgroundColor = [UIColor clearColor];

label1.text = @"Red";

[container addSubview:label1];

UILabel *label2 =[[UILabel alloc] initWithFrame:CGRectMake(40, 60, 60, 20)];

label2.backgroundColor = [UIColor clearColor];

label2.text = @"Green";

[container addSubview:label2];

UILabel *label3 =[[UILabel alloc] initWithFrame:CGRectMake(40, 90, 60, 20)];

label3.backgroundColor = [UIColor clearColor];

label3.text = @"Blue";

[container addSubview:label3];

// idebug 增加

UILabel *questionText2 = [[UILabel alloc] initWithFrame:CGRectMake(0,130,300,20)];

questionText2.backgroundColor = [UIColor clearColor];

[questionText2 setAdjustsFontSizeToFitWidth:YES];

questionText2.text = @"2. Diaoyu islands belong to which country?";

[container addSubview:questionText2];

RadioButton *rb11 = [[RadioButton alloc] initWithGroupId:@"second group" index:0];

RadioButton *rb12 = [[RadioButton alloc] initWithGroupId:@"second group" index:1];

RadioButton *rb13 = [[RadioButton alloc] initWithGroupId:@"second group" index:2];

rb11.frame = CGRectMake(10,160,22,22);

rb12.frame = CGRectMake(10,190,22,22);

rb13.frame = CGRectMake(10,220,22,22);

// 设置一个默认选项

[rb11 setChecked:YES];

[container addSubview:rb11];

[container addSubview:rb12];

[container addSubview:rb13];

UILabel *label11 =[[UILabel alloc] initWithFrame:CGRectMake(40, 160, 60, 20)];

label11.backgroundColor = [UIColor clearColor];

label11.text = @"China";

[container addSubview:label11];

UILabel *label22 =[[UILabel alloc] initWithFrame:CGRectMake(40, 190, 60, 20)];

label22.backgroundColor = [UIColor clearColor];

label22.text = @"China";

[container addSubview:label22];

UILabel *label33 =[[UILabel alloc] initWithFrame:CGRectMake(40, 220, 60, 20)];

label33.backgroundColor = [UIColor clearColor];

label33.text = @"China";

[container addSubview:label33];

[RadioButton addObserverForGroupId:@"first group" observer:self];

[RadioButton addObserverForGroupId:@"second group" observer:self];

UIButton *submitBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];

submitBtn.frame = CGRectMake(40, 280, 300-60, 40);

[submitBtn setTitle:@"提交答案" forState:UIControlStateNormal];

[submitBtn addTarget:self action:@selector(submitClick:) forControlEvents:UIControlEventTouchUpInside];

[self.view addSubview:submitBtn];

_dic = [[NSMutableDictionary alloc] initWithCapacity:16];

}

-(void)submitClick:(id)sender

{

NSLog(@"dic=%@",self.dic);

UILabel *resultLbl =[[UILabel alloc] initWithFrame:CGRectMake(40, 340, 240, 30)];

resultLbl.backgroundColor = [UIColor whiteColor];

resultLbl.textColor = [UIColor redColor];

NSMutableString *resultStr = [[NSMutableString alloc] initWithCapacity:16];

for (NSString *str in [self.dic allValues]) {

[resultStr appendFormat:@" %@,",str];

}

resultLbl.text = resultStr;

[self.view addSubview:resultLbl];

}

-(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString *)groupId{

NSLog(@"changed to %d in %@",index,groupId);

[_dic setObject:[NSString stringWithFormat:@"%d",index+1] forKey:groupId];

}

- (void)viewDidUnload

{

[super viewDidUnload];

// Release any retained subviews of the main view.

// e.g. self.myOutlet = nil;

}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

{

// Return YES for supported orientations

return (interfaceOrientation == UIInterfaceOrientationPortrait);

}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,189评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,577评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 150,857评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,703评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,705评论 5 366
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,620评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,995评论 3 396
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,656评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,898评论 1 298
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,639评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,720评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,395评论 4 319
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,982评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,953评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,195评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 44,907评论 2 349
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,472评论 2 342

推荐阅读更多精彩内容