项目中有个需求,就是仿照页数进行选择,有首页和尾页,这里简单写了个demo,代码如下:
1、创建button
for (int i=0; i<10; i++) { UIButton *btns=[UIButton buttonWithType:UIButtonTypeCustom]; btns.frame=CGRectMake(35+(i%3)*60, 100+(i/3)*40, 50, 30); [btns addTarget:self action:@selector(changeClick:) forControlEvents:UIControlEventTouchUpInside]; btns.tag=100+i; btns.backgroundColor=UIColor.lightGrayColor; [btns setTitle:[NSString stringWithFormat:@"%d",i] forState:UIControlStateNormal]; [self.view addSubview:btns]; } //首页按钮 UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeCustom]; [leftBtn addTarget:self action:@selector(changeClickTwo:) forControlEvents:UIControlEventTouchUpInside]; leftBtn.backgroundColor=UIColor.blueColor; leftBtn.frame=CGRectMake(20, 300, 50, 30); leftBtn.tag=609; [self.view addSubview:leftBtn]; //尾页按钮 UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeCustom]; [rightBtn addTarget:self action:@selector(changeClickTwo:) forControlEvents:UIControlEventTouchUpInside]; rightBtn.backgroundColor=UIColor.blueColor; rightBtn.frame=CGRectMake(200, 300, 50, 30); rightBtn.tag=610; [self.view addSubview:rightBtn];
如果需要第一个按钮默认选中,在上面的for循环里面添加如下代码:
if (i==0) { self.temBtn=btns; self.temBtn.backgroundColor=UIColor.redColor; }
具体的方法实现:
//单选效果 -(void)changeClick:(UIButton *)button{ for (int i=0; i<10; i++) { if (button.tag==100+i) { button.selected=YES; button.backgroundColor=[UIColor redColor]; self.temBtn=button; continue; } UIButton *btn=(UIButton *)[self.view viewWithTag:i+100]; btn.selected=NO; btn.backgroundColor=UIColor.lightGrayColor; } } //选中首页和尾页 -(void)changeClickTwo:(UIButton *)button{ if (button.tag==609) { for (int i=0; i<10; i++) { UIButton *btn=(UIButton *)[self.view viewWithTag:i+100]; if (self.temBtn==btn) { self.temBtn.backgroundColor=[UIColor lightGrayColor]; }else{ if (btn.tag==100) { btn.backgroundColor=UIColor.redColor; self.temTwoBtn=btn; }else{ if (self.temTwoBtn==btn) { self.temTwoBtn.backgroundColor=UIColor.lightGrayColor; }else{ if (btn.tag==100) { btn.backgroundColor=UIColor.redColor; } btn.backgroundColor=UIColor.lightGrayColor; } } } } }else{ for (int i=0; i<10; i++) { UIButton *btn=(UIButton *)[self.view viewWithTag:i+100]; if (self.temTwoBtn==btn) { self.temTwoBtn.backgroundColor=[UIColor lightGrayColor]; }else{ if (btn.tag==109) { btn.backgroundColor=UIColor.redColor; }else{ btn.backgroundColor=UIColor.lightGrayColor; } } } } }
方法可能写的有点low,不过功能是显示了!效果图就不上传了,希望能帮到大家!