iOS 实现多个按钮,点选一个其它都取消选中状态的最佳方法
2015-12-25 15:31
661 查看
首先我们先定义一个中间变量
然后在ViewDidLoad方法里,创建四个按钮,设置它们属性,以及点击方法,在此外设置中间变量tmpBtn = nil;
下面来看buttonselected:里面的实现过程
代码直接粘贴可用。
@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!= btn && _tmpBtn!=nil){ _tmpBtn.selected = NO; sender.selected = YES; _tmpBtn = btn; } }
代码直接粘贴可用。
相关文章推荐
- iOS文件下载
- iOS文件上传
- iOS代理、block传值
- iOS Quartz2D简单的使用
- WWDC 2014 Session笔记 - iOS界面开发的大一统
- IOS开发 3DTouch
- iOS 设置导航栏之二(设置导航栏的颜色、文字的颜色、左边按钮的文字及颜色)
- iOS Quartz 2D绘图用CGContextRef绘制三角形 —— HERO博客
- 我的第一次份实习工作-iOS实习生-第二个月
- iOS Kernel Exploitation Training (April 2015)
- iOS给label添加下划线
- IOS 中关于自定义Cell 上的按钮 开关等点击事件的实现方法(代理)
- ios编程之Core Data(一)
- iOS开发~CocoaPods使用详细说明
- IOS学习笔记之KVC、KVO
- 我的第一次份实习工作-iOS实习生-第一个月
- IOS Block 反向传值
- iOS: 懒加载
- 跳转到wifi设置页面 iOS
- iOS 设置导航栏的颜色和导航栏上文字的颜色