您的位置:首页 > 移动开发 > IOS开发

【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 控件