RadioButton, 单选按钮, iOS系统并没有提供这个控件, 项目中遇到了, 只好自己DIY了:
// MHRadioButton.h
#import <UIKit/UIKit.h>
static const NSUInteger kRadioButtonWidth = 22;
static const NSUInteger kRadioButtonHeight = 22;
@protocol MHRadioButtonDelegate <NSObject>
- (void)radioButtonSelectedAtIndex:(NSUInteger)index
inGroup:(NSString *)groupID;
@end
@interface MHRadioButton : UIView
- (instancetype)initWithGroupId:(NSString *)groupId
atIndex:(NSUInteger)index;
- (void)selected;
+ (void)addObserver:(id <MHRadioButtonDelegate>)observer
forFroupId:(NSString *)groupId;
+ (NSUInteger)getIndexWithGroupId:(NSString *)groupId;
@end
封装的这个类, 提供四个对外接口, 两个实例方法用于创建和设置RadioButton:
initWithGroupId: atIndex: 传入一个字符串和一个数字, 分别表示创建的RadioButton的组号以及下标.RadioButton必须是以组的方式出现, 例如表示性别的"男"和"女", 那么就可以如下创建:
NSString *sexGroupId = @"SEX";
MHRadioButton *maleRadioBtn = [[MHRadioButton alloc] initWithGroupId:sexGroupId atIndex:0];
MHRadioButton *femaleRadioButton = [[MHRadioButton alloc] initWithGroupId:sexGroupId atIndex:1];
然后把它们放到它们应该待的地方就OK了(像它们父母UIView一样设置它们的frame).
同组的RadioButton的组号必须相同, 不然就成多组RadioButton了.
创建好了, 你也可以指定某个RadioButton为默认选中状态:
[femaleRadioButton selected];
也就是, "SEX"组的RadioButton中, 设置了femaleRadioButton为默认选中状态了; 如果不设置, maleRadioButton为默认选中状态, 也就是每组第一个initWithGroupId: atIndex:创建的那个RadioButton为默认选中状态.
创建和设置完之后, 就是获取相应组的选中状态了. 封装的这个类中有两种方式可以获取:
一种是给这组RadioButton添加观察者:
[MHRadioButton addObserver:self forFroupId:sexGroupId];
当然这样你必须要遵从MHRadioButtonDelegate协议, 并实现协议中的方法:
- (void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString *)groupId;
groupId即表示组号, index即表示该组中被选中的RadioButton的下标. 这样你就可以在这个方法里实现监控按钮状态改变的处理逻辑了.
另一种方式是直接调用另一个类方法了:
NSUInteger *index = [MHRadioButton getIndexWithGroupId:sexGroupId];
这种方法你可以根据组号获取该组中那个RadioButton被选中了.
上述两种方式各有优点吧, 第一种遵从协议,实现代理方法, 可能感觉有点麻烦, 但是可以实时实现对每组按钮选中状态的控制; 第二中方式省去了协议和代理, 可以在最后需要获取RadioButton状态的时候直接获取. 如果你没必要关心用户在点击RadioButton时的操作, 这时第二种方式无疑是最优的.
源码下载(拉取项目中libs文件夹下地两个文件, 就可以按照上述方法使用了)