自定义UISwitch,可实现自定义开关图片和背景色

效果如图所示:


自定义UISwitch

iOS7.0之后无法自定义UISwitch的图片,而在日常的开发需求中,又不可能只有一种开关样式,UI所设计的开关样式千奇百怪,那么系统所提供的开关样式已经不足以满足我们的开发需求了。所以这时候我们就需要自定义开关了。
自定义开关,我们剖析下开关的结构,在系统的UISwitch中,我们可以看出,通过调用 onImage 或者 offImage 属性来设置开关的图片,但是这两个方法在 iOS 6 之后已经被弃用掉了。

NS_CLASS_AVAILABLE_IOS(2_0) __TVOS_PROHIBITED @interface UISwitch : UIControl <NSCoding>

@property(nullable, nonatomic, strong) UIColor *onTintColor NS_AVAILABLE_IOS(5_0) UI_APPEARANCE_SELECTOR;
@property(null_resettable, nonatomic, strong) UIColor *tintColor NS_AVAILABLE_IOS(6_0);
@property(nullable, nonatomic, strong) UIColor *thumbTintColor NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;

@property(nullable, nonatomic, strong) UIImage *onImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;
@property(nullable, nonatomic, strong) UIImage *offImage NS_AVAILABLE_IOS(6_0) UI_APPEARANCE_SELECTOR;

@property(nonatomic,getter=isOn) BOOL on;

- (instancetype)initWithFrame:(CGRect)frame NS_DESIGNATED_INITIALIZER;      // This class enforces a size appropriate for the control, and so the frame size is ignored.
- (nullable instancetype)initWithCoder:(NSCoder *)aDecoder NS_DESIGNATED_INITIALIZER;

- (void)setOn:(BOOL)on animated:(BOOL)animated; // does not send action
@end

那么,我们自定义开关所要暴露出来的属性就要有

  • 开关开着时的图片
  • 开关关着时的图片
  • 开关的背景色
  • 开关的状态
    在这里,我们可以将开关分为如图所示两部分结构:


    自定义开关结构

    其中,B为开关提供底部背景色值,A为开关提供开关状态色值,点击开关,A可以左右滑动,并改变状态。

思路:

  • 添加点击事件,改变自身状态
  • 添加观察者观察自身状态的改变
  • 通过判断自身状态,显示自身样式

主要代码如下所示:

@interface BKSwitch : UIControl
@property (nonatomic, assign) BOOL on;
@property (nonatomic, strong) UIView *roundView;//滑块view
@end


@implementation BKSwitch

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self addObserver:self forKeyPath:@"isOn" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
        [self addTarget:self action:@selector(translateAni) forControlEvents:UIControlEventTouchUpInside];
        [self creatView];
    }
    return self;
}

-(void)creatView{
    self.backgroundColor = [UIColor whiteColor];
    self.clipsToBounds = YES;
    self.layer.cornerRadius = self.bounds.size.height/2;
    self.layer.borderColor = [UIColor grayColor].CGColor;
    self.layer.borderWidth = .5;
    
    self.roundView = [[UIView alloc]initWithFrame:CGRectMake(0, 1, self.bounds.size.height-2, self.bounds.size.height-2)];
    self.roundView.layer.cornerRadius = self.bounds.size.height/2;
//    self.roundView.backgroundColor = [UIColor whiteColor];
    self.roundView.userInteractionEnabled = NO;
    [self addSubview:self.roundView];
//    self.roundView.layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
//    self.roundView.layer.shadowOffset = CGSizeMake(0,0);//shadowOffset阴影偏移,x向右偏移4,y向下偏移4,默认(0, -3),这个跟shadowRadius配合使用
//    self.roundView.layer.shadowOpacity = 0.5;//阴影透明度,默认0
//    self.roundView.layer.shadowRadius = 2;//阴影半径,默认3
}

-(void)setOn:(BOOL)on{
    if (on) {
        self.roundView.frame = CGRectMake(self.bounds.size.width-self.roundView.bounds.size.width-1, 1,           self.bounds.size.height-2, self.bounds.size.height-2);
        self.roundView.roundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"switchOn"]];
        self.roundView.backgroundColor = OCTColorFromRGB(0xffe100);
        self.roundView.layer.borderColor = OCTColorFromRGB(0xffe100).CGColor;
    }else{
        self.roundView.frame = CGRectMake(0, 1, self.bounds.size.height-2, self.bounds.size.height-2);
        self.roundView.roundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"switchOff"]];
        self.roundView.backgroundColor = OCTColorFromRGB(0xc9c9c9);
        self.roundView.layer.borderColor = OCTColorFromRGB(0xc9c9c9).CGColor;
    }
    self.isOn = on;
}

-(BOOL)on{
    return self.isOn;
}

- (void)translateAni{
    CGRect rect = self.roundView.frame;
    [UIView animateWithDuration:0.3 animations:^{
        self.roundView.frame = rect;
    }];
    if (!self.isOn){
        rect.origin.x = self.bounds.size.width - self.roundView.bounds.size.width - 1;
    }else{
        rect.origin.x = 0;
    }
    [UIView animateWithDuration:0.3 animations:^{
        self.roundView.frame = rect;
    }completion:^(BOOL finished) {
    }];
    self.isOn = !self.isOn;
}

//监听isON
//keyPath:属性名称
//object:被观察的对象
//change:变化前后的值都存储在change字典中
//context:注册观察者时,context传过来的值
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

-(void)dealloc
{
    [self removeObserver:self forKeyPath:@"isOn"];
}

@end

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

推荐阅读更多精彩内容

  • 光阴如流水, 一去不复还。 明日何其多, 人生笑谈间。 即月就退休, 感慨吐心言。 韶华人生路, 教育职责担。 从...
    王成元阅读 1,792评论 3 4
  • 有时候我们会不明白,为什么一个看上去很坏的人,还有人很爱很爱他。当花千骨为了解白子画的卜元鼎之毒不惜成为全天下的“...
    田小等阅读 2,629评论 0 1
  • 《忽晓前顾后》 呼中书,花音婉, 说谋其探不饶人。 钱希处,画墨怜, 怡型城出春已晨。 沙趣易舍录清纱, 滴离必洒...
    春城怡景阅读 2,761评论 0 22
  • 你总被人欺负,是因为错把软弱当成了善良。在经济困难时遇到借钱的朋友,你不好意思拒绝所以慷慨解囊,结果那人迟迟不肯还...
    北遥_阅读 3,541评论 0 1

友情链接更多精彩内容