按钮切换效果

时间:2022-02-02 23:13:59

两个按钮实现点击切换,切换后加载具体的控件及实现功能。通过UIView 来实现滑块的效果。

//定义两个变量

@interface ForumsViewController (){

    UIButton *_oldBtn;

}

//滑块

@property (nonatomic,strong)UIView *slider;


@end


- (void)createTopView{

    UIView *topView = [[UIViewalloc]initWithFrame:CGRectMake(0,0, F_DEVICE_W,64)];

    topView.backgroundColor = [UIColorblueColor];

    [self.viewaddSubview:topView];

    NSArray *itemArray =@[@"社交",@"发现"];

    //滑块

    self.slider = [[UIViewalloc]initWithFrame:CGRectMake(F_DEVICE_W / 3.f, 22,F_DEVICE_W / 6.f,35)];

    self.slider.backgroundColor = [UIColorwhiteColor];

     self.slider.layer.cornerRadius = 5;

     self.slider.layer.masksToBounds = YES;

     [topView addSubview:self.slider];

    

    for (NSInteger i =0; i < itemArray.count; i++) {

        UIButton *btn = [UIButtonbuttonWithType:UIButtonTypeCustom];

        btn.frame =CGRectMake(F_DEVICE_W /3.f + i * F_DEVICE_W /6.f, 20,F_DEVICE_W / 6.f  ,44);

        btn.backgroundColor = [UIColorclearColor];

        btn.tag =9998 + i;

        if (i ==0) {btn.selected =YES;_oldBtn = btn;}

        [btn setTitle:itemArray[i]forState:UIControlStateNormal];

        [btn setTitleColor:[UIColorblueColor] forState:UIControlStateSelected];

        [btn setTitleColor:[UIColorwhiteColor] forState:UIControlStateNormal];

        [btn addTarget:selfaction:@selector(btnClickAction:)forControlEvents:UIControlEventTouchUpInside];

        [topView addSubview:btn];

    }

}


- (void)btnClickAction:(UIButton *)sender{

    if (sender.selected)return;

    _oldBtn.selected =NO;//选中的老按钮选中状态直为非选中

    sender.selected =YES;

    _oldBtn = sender;

   

    __weak typeof(self) bSelf =self;

    switch (sender.tag) {

        case9998:{

            [UIViewanimateWithDuration:0.5animations:^{

                bSelf.slider.frame =CGRectMake(F_DEVICE_W /3.f, 22,F_DEVICE_W / 6.f,40);

            }];

//此处添加其他事件

            break;}

        case9999:{

            [UIViewanimateWithDuration:0.5animations:^{

                bSelf.slider.frame =CGRectMake(F_DEVICE_W *0.5, 22,F_DEVICE_W / 6.f,40);

            }];

//此处添加其他事件

            break;}

        default:

            break;

    }

}