第一,定义一个全局的按钮变量
- /**
- * 按钮选中,中间值
- */
- @property (nonatomic,strong) UIButton *selectedBtn;
第二,添加多个按钮到scrollView中
- /**
- * 创建按钮添加到scrollView
- */
- -(void)creatBtn
- {
- int i = 0;
- NSArray *titleArray = @[@"头条",@"热点",@"体育",@"北京",@"订阅",@"财经",@"科技",@"汽车",@"时尚",@"图片",@"跟帖",@"房产",@"直播",@"轻松一刻",@"军事",@"历史"];
- for (NSString *title in titleArray) {
- UIButton *btn = [[UIButton alloc] init];
- btn.frame = CGRectMake(i*pading + _tempW, 0, 50, 50);
- [btn setTitle:title forState:UIControlStateNormal];
- btn.tag = i;
- btn.contentMode = UIViewContentModeCenter;
- [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
- [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
- [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
- [btn addTarget:self action:@selector(titleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
- [btn sizeToFit];
- _tempW += btn.frame.size.width;
- [self.btnView addSubview:btn];
- i++;
- }
- }
第三,监听按钮的点击,切换选中按钮
- -(void)titleBtnClick:(UIButton *)btn
- {
- if (btn!= self.selectedBtn) {
- self.selectedBtn.selected = NO;
- btn.selected = YES;
- self.selectedBtn = btn;
- }else{
- self.selectedBtn.selected = YES;
- }
- // if (self.selectedBtn == nil) {
- // btn.selected = YES;
- // self.selectedBtn = btn;
- // }else if (self.selectedBtn != nil&&self.selectedBtn == btn){
- // btn.selected = YES;
- // }else if (self.selectedBtn != btn&&self.selectedBtn != nil){
- // self.selectedBtn.selected = NO;
- // btn.selected = YES;
- // self.selectedBtn = btn;
- // }
- }