暂不支持 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