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

2016-11-02  本文已影响0人  再也不要见

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

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

}

上一篇下一篇

猜你喜欢

热点阅读