按钮切换效果

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

//定义两个变量

@interface ForumsViewController (){

    UIButton *_oldBtn;

}

//滑块

@property (nonatomic,strong)UIView *slider;


@end


- (void)createTopView{

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

    topView.backgroundColor = [UIColor blueColor];

    [self.view addSubview:topView];

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

    //滑块

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

    self.slider.backgroundColor = [UIColor whiteColor];

     self.slider.layer.cornerRadius = 5;

     self.slider.layer.masksToBounds = YES;

     [topView addSubview:self.slider];

    

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

        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];

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

        btn.backgroundColor = [UIColor clearColor];

        btn.tag = 9998 + i;

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

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

        [btn setTitleColor:[UIColor blueColor] forState:UIControlStateSelected];

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

        [btn addTarget:self action:@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) {

        case 9998:{

            [UIView animateWithDuration:0.5 animations:^{

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

            }];

//此处添加其他事件

            break;}

        case 9999:{

            [UIView animateWithDuration:0.5 animations:^{

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

            }];

//此处添加其他事件

            break;}

        default:

            break;

    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值