iOS UISwitch在按钮上加文字 自定义文字颜色 按钮颜色 背景颜色

        通过苹果原有的UISwitch的属性还无法给按钮上加上文字,无法自定义各个部分的颜色。所以就自定义一个类继承UIView,加上点击手势来仿写一个UISwitch。

        本文只讲实现原理,代码未经任何封装。想直接使用现成的封装好的控件,可移步文末下载Demo。Demo中自定义控件XYSwitch拖入到项目中使用,已封装好接口设置各个参数。

        本控件无需依赖任何第三方库/插件。

自定义UIView属性列表

//switch的按钮

@property(nonatomic,strong)UIView* buttonView;

//switch上的文字

@property(nonatomic,strong)UILabel* contentLabel;

//点击手势

@property(nonatomic,strong)UITapGestureRecognizer* tapRecognizer;

//记录switch的状态(开/关)

@property(nonatomic,assign)BOOL isOn;

        使用使用点击手势获取用户的点击,在监听事件里,根据开关的状态调用不同的UI布局

首先要设置初始的UI布局

- (void)frameSetup  {

        CGFloat x,y,w,h;

        x = 2;

        y = 2;

        w = self.frame.size.height - 2 * 2;

        h = self.frame.size.height - 2 * 2;

        self.btnView.frame = CGRectMake(x, y, w, h);

        self.btnView.layer.cornerRadius = w / 2;

        self.btnView.layer.masksToBounds = YES;

        x = 0;

        y = 0;  

        self.contentLabel.frame = CGRectMake(x, y, w, h);  

        self.layer.cornerRadius = self.frame.size.height * 0.5;  

        self.layer.masksToBounds = YES;

}

UITapGestureRecognizer点击事件代码

//改变开关状态

- (void)changeState {

        __weakXYSwitch * weakSelf = self;

        self.isOn = !self.isOn;  

        //block非空判断,不写会崩溃

        if (self.changeStateBlock) {      

                self.changeStateBlock(self.isOn);

        } else {

                NSLog(@"self.changeStateBlock() is nil");

        }

        //UIView动画改变UI布局

        if (self.isOn) {

                [UIView animateWithDuration:0 animations:^{

                        [weakSelf stateOn];

                }];

        }else{

                [UIView animateWithDuration:0 animations:^{

                        [weakSelf stateOff];

                }];

        }

}

核心代码(即改变按钮的frame来仿照UISwitch的开和关)

- (void)stateOff {   //关闭状态的UI

    self.backgroundColor = self.bgOffColor;

    self.btnView.backgroundColor = self.btnOffColor;

    self.contentLabel.textColor = self.textOffColor;

    self.contentLabel.text = self.offText;


    CGFloat x,y,w,h;

    x = 2;

    y = 2;

    w = self.frame.size.height-2*2;

    h = self.frame.size.height-2*2;

    self.btnView.frame = CGRectMake(x, y, w, h);

}


- (void)stateOn {  //打开状态的UI

    self.backgroundColor = self.bgOnColor;

    self.btnView.backgroundColor = self.btnOnColor;

    self.contentLabel.textColor = self.textOnColor;

    self.contentLabel.text = self.onText;


    CGFloat x,y,w,h;

    x = self.frame.size.width - self.btnView.frame.size.width - 2;

    y =2;

    w = self.frame.size.height-2*2;

    h = self.frame.size.height-2*2;

    self.btnView.frame = CGRectMake(x, y, w, h);

}


        实现原理讲解就到此结束了。


        自定义UIView 的好处,可以自己随意改变任意控件的颜色、大小和内容。

效果图:

自定义Switch效果图


    附Demo地址: github.com/DXY123/XYSwitch

最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容