单选Btn

来源:互联网 发布:新中新dkq a16d软件 编辑:程序博客网 时间:2024/06/07 04:43

效果预览

一、思路解析

充分利用button的select属性,设置button的选中及非选中状态。设置一个全局的选中button(当前选中的button),这样一个简单的单选功能就实现了。

二、具体源码

(1)准备工作:

@property (nonatomic,strong) UIView *SearchTopview;

@property (nonatomic,weak) UIButton *Selectbutton;

#pragma mark - getter and setter

- (UIView *)SearchTopview{

if (_SearchTopview == nil) {

_SearchTopview = [[UIView alloc] init];

_SearchTopview.frame = CGRectMake(0, 0, SCREEN_WIDTH, 100);

}

return _SearchTopview;

}

(2)首先一个for循环设置按钮

UILabel *lbTitle = [[UILabel alloc]init];

lbTitle.frame = CGRectMake(10, 0, SCREEN_WIDTH - 20, 30);

lbTitle.textAlignment = NSTextAlignmentLeft;

lbTitle.text = @"选择你要的搜索分类";

lbTitle.textColor = [UIColor grayColor];

lbTitle.font = HiraginoMidFONT;

[self.SearchTopview addSubview:lbTitle];

NSArray *titlearray = @[@"资讯",@"餐答",@"秀场",@"厨师",@"掌柜",@"秘籍",@"课堂",@"产品",@"悬赏",@"人物志"];

int col = 4;

int margin = 10;

for (int i = 0; i < titlearray.count; i++) {

int page = i/col;

int index = i%col;

UIButton *BtnSearch = [[UIButton alloc]initWithFrame:CGRectMake(margin + index*(SCREEN_WIDTH - (col + 1)*margin)/col + margin*index,40*page + 40,(SCREEN_WIDTH - (col + 1)*margin)/col,30 )];

BtnSearch.layer.cornerRadius = 5;

BtnSearch.layer.masksToBounds = YES;

BtnSearch.layer.shadowOffset =  CGSizeMake(1, 1);

BtnSearch.layer.shadowOpacity = 0.8;

BtnSearch.layer.shadowColor =  [UIColor blackColor].CGColor;

BtnSearch.backgroundColor = [UIColor lightGrayColor];

BtnSearch.tag = i;

[BtnSearch setTitle:titlearray[i] forState:UIControlStateNormal];

[BtnSearch setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];

[BtnSearch setTitleColor:BackyellowColor forState:UIControlStateSelected];

BtnSearch.titleLabel.font = HiraginoMidFONT;

[BtnSearch addTarget:self action:@selector(SelectBtnSearch:) forControlEvents:UIControlEventTouchUpInside];

if (i == 0) {

BtnSearch.backgroundColor = BackblackColor;

BtnSearch.selected = YES;

self.Selectbutton = BtnSearch;

}

[self.SearchTopview addSubview:BtnSearch];

}

self.SearchTopview.height = [CalculationTool rowWithcount:titlearray.count andcol:col]*40 + 45;

(3)按钮事件

#pragma mark - event

- (void)SelectBtnSearch:(UIButton *)Btn{

if (!Btn.isSelected) {

self.Selectbutton.selected = !self.Selectbutton.selected;

self.Selectbutton.backgroundColor = [UIColor lightGrayColor];

Btn.selected = !Btn.selected;

Btn.backgroundColor = BackblackColor;

self.Selectbutton = Btn;

}

}

(4)按钮事件 简述

if (!Btn.isSelected):使点击当前按钮是不执行事件

self.Selectbutton.selected = !self.Selectbutton.selected;  Btn.selected = !Btn.selected;

已经选中的按钮(self.Selectbutton)及当前点击按钮(Btn)的取反 使选中按钮为!select状态,单击按钮为selectt状态

self.Selectbutton = Btn; 所以现在的选中按钮就替换为你现在所点击的按钮了。



链接:http://www.jianshu.com/p/41d378ec6050
原创粉丝点击