【iOS】单选按钮控件
2017-02-20 09:01
375 查看
目标
木错,就是这个在Windows上面很常见的东西,而在iOS里面,并没有这个控件可供使用…那么肿么办?就只能自己做呗…分析
个人首先从用户交互上面分析了这个东西,首先它被触摸时及选中,其次在其他按钮被选中时,它能够撤销原有的选择状态。所以么,这个东西要有这些基本特点:- 触摸时响应操作,触发选中状态
- 触摸其他按钮时会被撤销选中状态,及要有方法能够撤销单个按钮的选中状态
- 可能根据选项不同有不同的大小
因此,个人选择通过继承UIControl来实现这个空间类
编码
根据分析,控件需要有两种状态,而软件开启时可能被默认置于一种状态,及需要方法来设置选中和非选中状态,并需要一个属性来标记当前的状态,因为选择属性的直接更改会导致显示不同步,因此将属性设置为readonly~~~ Objective-C
import
- (void)drawRect:(CGRect)rect { // Drawing code CGContextRef context = UIGraphicsGetCurrentContext(); CGContextSetFillColorWithColor(context, [UIColor colorWithRed:187.0/255.0 green:221.0/255.0 blue:211.0/255.0 alpha:1.0].CGColor); CGContextAddEllipseInRect(context, CGRectMake(0, 0, CGRectGetWidth(self.frame), CGRectGetHeight(self.frame))); CGContextFillPath(context); CGContextSetFillColorWithColor(context, [UIColor whiteColor].CGColor); CGContextAddEllipseInRect(context, CGRectMake(CGRectGetWidth(self.frame) * 0.1, CGRectGetHeight(self.frame) * 0.1,CGRectGetWidth(self.frame) * 0.8, CGRectGetHeight(self.frame) * 0.8)); CGContextFillPath(context); if (_isSelected == YES) { CGContextSetFillColorWithColor(context, [UIColor colorWithRed:187.0/255.0 green:221.0/255.0 blue:211.0/255.0 alpha:1.0].CGColor); CGContextAddEllipseInRect(context, CGRectMake(CGRectGetWidth(self.frame) * 0.3, CGRectGetHeight(self.frame) * 0.3,CGRectGetWidth(self.frame) * 0.4, CGRectGetHeight(self.frame) * 0.4)); CGContextFillPath(context); } }
然后编写触摸响应,在进行触摸时,若按钮为非选中状态,则需要变为选择状态,并通过setNeedDisplay来刷新现实
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{ printf("is touched"); [super touchesBegan:touches withEvent:event]; if (_isSelected == NO) { printf("is touched"); _isSelected = YES; [self setNeedsDisplay]; } }
随后是选中和取消选中的方法,只需要更改属性值并重新绘制就可以了
- (void)select{ _isSelected = YES; [self setNeedsDisplay]; } - (void)deSelect{ _isSelected = NO; printf("deSelect"); [self setNeedsDisplay]; }
github中相关的项目
明显有些人这做的比我好很多,我是在我完成制作之后才去参考了别人的项目,发现其实还有很多很有趣的拓展方法例如这个(https://github.com/onegray/RadioButton-ios) ,这个项目通过Outlet实现了直接关联多个按钮
相关文章推荐
- iOS开发系列之常用自定义控件开发集—自定义单选按钮或者多选按钮控件开发
- VC常用小技巧(二) ---单选按钮控件(Radio Button)的使用
- VC单选按钮控件(Radio Button)用法(转)
- UIButton按钮控件-iOS开发
- iOS-自定义单选复选按钮
- VC单选按钮控件(Radio Button)用法
- CheckBox(复选按钮)/RadioButton(单选按钮)/BulletedList控件
- 单选按钮控件使用心得
- VC单选按钮控件Radio Button用法
- UIButton 按钮控件-IOS开发
- 常用控件 05 单选按钮 Radio Buttons
- 单选按钮显示隐藏控件
- VC单选按钮控件(Radio Button)用法
- VC单选按钮控件(Radio Button)用法(转)
- UIButton 按钮控件-IOS开发
- VC单选按钮控件(Radio Button)用法(转)
- VC单选按钮控件(Radio Button)用法
- asp.net 性别 单选按钮 操作Radiobutton控件
- VC单选按钮控件(Radio Button)用法
- UIButton 按钮控件-IOS开发