iOS 实现多个按钮,点选一个其它都取消选中状态的最佳方法
2015-11-16 12:56
781 查看
iOS 实现多个按钮,点选一个其它都取消选中状态的最佳方法
在做项目过程中,特别是商城类的项目、学习考试类的项目中,通常会有根据销量,价格,时间排序,以及单项选则题这样的要求。先说一下原理,就是利用中间变量来记录某个选中状态的按钮,加一个判断,如果用户下一次点击的不是这个按钮那么用中间变量把这个按钮的选中状态取消掉,再把新的按钮赋值给中间变量,这能保证选中状态的惟一性。这里是OC 应用在iOS 项目中的,下面来看具体实现。
首先我们先定义一个中间变量
@property (strong,nonatomic)UIButton * tmpBtn;然后在ViewDidLoad方法里,创建四个按钮,设置它们属性,以及点击方法,在此外设置中间变量tmpBtn = nil;
—(void)viewDidLoad{ NSArray * array = [NSArray arrayWithObjects:@"默认",@"销量",@"价格",@"时间", nil]; for (int i = 0; i<4; i ++) { UIButton * button = [[UIButton alloc]initWithFrame:CGRectMake(80*i, 0, 80, 40)]; [button setTitle:[array objectAtIndex:i] forState:UIControlStateNormal]; [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal]; [button setTitleColor:[UIColor blackColor] forState:UIControlStateSelected]; [button.titleLabel setFont:[UIFont systemFontOfSize:14]]; [button.layer setBorderWidth:0.3]; button.userInteractionEnabled = YES; [button addTarget:self action:@selector(buttonSelected:) forControlEvents:UIControlEventTouchUpInside]; [button setBackgroundColor:[UIColor whiteColor]]; [button setTag:i]; [self.view addSubview:button]; }
下面来看buttonselected:里面的实现过程
-(void)buttonSelected:(UIButton*)sender{ if (_tmpBtn == nil){ sender.selected = YES; _tmpBtn = sender; } else if (_tmpBtn !=nil && _tmpBtn == sender){ sender.selected = YES; } else if (_tmpBtn!= sender && _tmpBtn!=nil){ _tmpBtn.selected = NO; sender.selected = YES; _tmpBtn = sender; } }代码直接粘贴可用
相关文章推荐
- IOS基础 - 模态跳转方式
- IOS开发的报错(异常)信
- iOS菜鸟之FMDB的二次封装简单易用
- Xcode7.1与iOS9之坑 (持续更新)
- iOS开发框架篇—CoreImage
- iOS 定时器(NSTimer)的使用
- iOS开发指令篇—__weak修饰符详解
- 关于iOS 'The sandbox is not sync with the Podfile.lock'问题解决方法
- ios开发使用lipo命令合并真机库和模拟器库
- iOS应用性能优化的25个建议
- iOS实现倒计时
- Sara小妹开始入门iOS开发
- IOS解析XML
- iOS 9 适配系列教程
- iOS之 PJSIP静态库编译(二)
- iOS开发,获取手机型号,系统版本号,
- iOS 9 适配系列教程
- 梦维 iOS 文章系列 文摘
- iOS开发之iOS程序偏好设置(Settings Bundle)的使用
- iOS XCode启用/关闭Clang Warnings