ios 自定义RadioButton

1 前言

众所周知在IOS中没有单选按钮这一控件,今天我们来学习一下简单的单选控件。类似与Web中的radio表单元素。

2 详述

本控件单纯的利用按钮控件和NSObject的respondsToSelector方法来判断某一个类中是否存在某方法。

代码概述:

RadioButton.h(控件头文件):

 

[plain] view plaincopy
  1. #import <UIKit/UIKit.h>  
  2.   
  3.   
  4. @protocol RadioButtonDelegate <NSObject>  
  5.   
  6. -(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString*)groupId;  
  7. @end  
  8.   
  9. @interface ZYRadioButton : UIView{  
  10.     NSString *_groupId;  
  11.     NSUInteger _index;  
  12.     UIButton *_button;  
  13. }  
  14. //GroupId  
  15. @property(nonatomic,retain)NSString *groupId;  
  16. //Group的索引  
  17. @property(nonatomic,assign)NSUInteger index;  
  18.   
  19. //初始化RadioButton控件  
  20. -(id)initWithGroupId:(NSString*)groupId index:(NSUInteger)index;  
  21. //为  
  22. +(void)addObserverForGroupId:(NSString*)groupId observer:(id)observer;  
  23.   
  24. @end  

 

ViewController.m(视图控制器中的代理方法):

 

[plain] view plaincopy
  1. //代理方法  
  2. -(void)radioButtonSelectedAtIndex:(NSUInteger)index inGroup:(NSString *)groupId{  
  3.     NSLog(@"changed to %d in %@",index,groupId);  
  4. }  

 

运行结果:


选中某一选项后结果:


控制台显示结果:

 

2013-05-22 21:50:46.033 RadioButtonDemo[467:c07] changed to 0 in first group

Demo代码下载:http://download.csdn.net/detail/u010013695/5431201

 

原文地址:https://www.cnblogs.com/yulang314/p/3549615.html