iOS按钮切换效果

释放双眼,带上耳机,听听看~!

两个按钮实现点击切换,切换后加载具体的控件及实现功能。通过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;

   

    __weaktypeof(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;

    }

}

 

人已赞赏
iOS文章

iPhone设备分辨率及尺寸

2020-3-3 10:43:18

iOS文章

ios Masonry使用中equalTo和mas_equalTo的区别

2020-3-3 13:58:41

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
有新消息 消息中心
搜索