// h文件
import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface CLCustomSwitch : UIView
@property (nonatomic, assign, getter=isOn) BOOL on;
//滑块颜色
@property (nonatomic, strong) UIColor *sliderColor;
//开启状态 背景颜色
@property (nonatomic, strong) UIColor *openColor;
//关闭状态 背景颜色
@property (nonatomic, strong) UIColor *closedColor;
@property (nonatomic, copy) void (^switchBlock)(BOOL isOn);
@end
NS_ASSUME_NONNULL_END
// m 文件
import "CLCustomSwitch.h"
@implementation CLCustomSwitch
{
UIButton *_switchBtn;
UIImageView *_sliderView;
}
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
[self setupSubView];
}
return self;
}
-(void)setupSubView{
_switchBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, self.width, self.height)];
_switchBtn.backgroundColor=[UIColor grayColor];
_switchBtn.layer.masksToBounds=YES;
_switchBtn.layer.cornerRadius=_switchBtn.height/2.0;
[_switchBtn addTarget:self action:@selector(switchClick:) forControlEvents:UIControlEventTouchUpInside];
[self addSubview:_switchBtn];
//滑块
_sliderView = [[UIImageView alloc] initWithFrame:CGRectMake(1.5, 0, self.height-3, self.height-3)];
_sliderView.backgroundColor=[UIColor whiteColor];
_sliderView.layer.masksToBounds=YES;
_sliderView.layer.cornerRadius=_sliderView.height/2.0;
_sliderView.centerY=self.height/2.0;
[self addSubview:_sliderView];
}
-(void)setOpenColor:(UIColor *)openColor{
_openColor=openColor;
}
-(void)setClosedColor:(UIColor *)closedColor{
_closedColor=closedColor;
}
-(void)setOn:(BOOL)on{
_on = on;
float X=1.5;
if (on == YES) {
X=self.width-1.5-_sliderView.width;
_switchBtn.backgroundColor=_openColor;
}else{
X=1.5;
_switchBtn.backgroundColor=_closedColor;
}
[UIView animateWithDuration:0.2f animations:^{
self->_sliderView.x = X;
}];
if (_switchBlock) {
_switchBlock(_on);
}
}
-(void)switchClick:(UIButton *)btn{
self.on = !self.isOn;
}
@end
//使用
//名称开关
CLCustomSwitch *customSwitch = [[CLCustomSwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 25)];
customSwitch.openColor=rgb(239, 101, 50);
customSwitch.closedColor=[UIColor grayColor];
customSwitch.on=YES;
customSwitch.centerY=_SupView.height/2.0;
customSwitch.right=_SupView.width-15;
customSwitch.tag=10086;
[_SupView addSubview:customSwitch];
customSwitch.switchBlock = ^(BOOL isOn) {
if (isOn==YES) {
}else{
}
};
网友评论