自定义 UISwitch

暂不支持 Xib 拖放的方式创建

Demo下载地址 http://download.csdn.net/download/xiaofei125145/9565323

//
//  CLSwitch.h
//  UISwitchFremw
//
//  Created by Wangdy on 16/7/1.
//  Copyright © 2016年 Wangdy. All rights reserved.
//

#import <UIKit/UIKit.h>

@interface CLSwitch : UIControl

//事件类型  UIControlEventValueChanged
@property (nonatomic,assign)BOOL isOn;

//默认初始化方法, onImage 和 offImage 是必选参数不能为 nil,  frame.size 为无效值 ,size 根据图片size设置大小
- (instancetype)initWithOnImage:(UIImage *)onImage offImage:(UIImage *)offImage frame:(CGRect)frame;

@end


//
//  CLSwitch.m
//  UISwitchFremw
//
//  Created by Wangdy on 16/7/1.
//  Copyright © 2016年 Wangdy All rights reserved.
//

#import "CLSwitch.h"

@interface CLSwitch ()
@property(nonatomic,strong)UIImage *onImage;
@property(nonatomic,strong)UIImage *offImage;
@end

@implementation CLSwitch

- (instancetype)initWithFrame:(CGRect)frame {
    NSAssert(NO, @"请使用 -initWithOnImage:(UIImage *)onImage offImage:(UIImage *)offImage frame:(CGRect)frame 初始化CLSwitch");
    return nil;
}

- (instancetype)initWithOnImage:(UIImage *)onImage offImage:(UIImage *)offImage frame:(CGRect)frame{
    NSAssert(onImage&&offImage, @"onImage & offImage 不能为空");
    frame.size = onImage.size;
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundColor = [UIColor whiteColor];
        _onImage = onImage;
        _offImage = offImage;
        [self addTarget:self action:@selector(switchClicked) forControlEvents:UIControlEventTouchUpInside];
        self.isOn = NO;
    }
    return self;
}

- (void)switchClicked {
    self.isOn = !self.isOn;
    [self sendActionsForControlEvents:UIControlEventValueChanged];
}

- (void)setIsOn:(BOOL)isOn {
    _isOn = isOn;
    
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"contents"];
    animation.fromValue = self.layer.contents;
    animation.toValue = (id)(_isOn ? _onImage.CGImage: _offImage.CGImage);
    animation.duration = .3;
    [self.layer addAnimation: animation forKey: @"animation"];
    
    self.layer.contents = (id)(_isOn ? _onImage.CGImage: _offImage.CGImage);
}

- (void)setFrame:(CGRect)frame {
    if (_onImage) {
        frame.size = _onImage.size;
    }
    super.frame = frame;
}

- (CGSize)sizeThatFits:(CGSize)size {
    return _onImage.size;
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值