#import <UIKit/UIKit.h>
@interface MySlider : UIView
@property (nonatomic, assign) float value;
@property (nonatomic, assign) float maximumValue;
@property (nonatomic, assign) float minimumValue;
@end
#import "MySlider.h"
@interface MySlider ()
{
UIView *_tView;
}
@end
@implementation MySlider
- (instancetype)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
_minimumValue = 0;
_maximumValue = 1;
_tView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, frame.size.height)];
_tView.backgroundColor = [UIColor orangeColor];
[self addSubview:_tView];
self.backgroundColor = [UIColor magentaColor];
//点击手势
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didTap:)];
[self addGestureRecognizer:tap];
//拖动手势
UIPanGestureRecognizer *pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didPan:)];
[self addGestureRecognizer:pan];
}
return self;
}
- (float)valueForPosition:(CGPoint)point
{
return point.x * (_maximumValue - _minimumValue) / self.frame.size.width + _minimumValue;
}
- (void)didTap:(UITapGestureRecognizer *)recognizer
{
//获取拖动手势当前的位置
CGPoint location = [recognizer locationInView:self];
NSLog(@"tap location: %@", NSStringFromCGPoint(location));
self.value = [self valueForPosition:location];
}
- (void)didPan:(UIPanGestureRecognizer *)recognizer
{
//获取拖动手势当前的位置
CGPoint location = [recognizer locationInView:self];
NSLog(@"location: %@", NSStringFromCGPoint(location));
self.value = [self valueForPosition:location];
//获取拖动手势的相对位移
CGPoint point = [recognizer translationInView:self];
NSLog(@"%@", NSStringFromCGPoint(point));
}
- (void)setValue:(float)value
{
if (value <= _minimumValue) {
_value = _minimumValue;
}
else if (value >= _maximumValue) {
_value = _maximumValue;
}
else {
_value = value;
}
[self setNeedsLayout];
}
- (void)layoutSubviews
{
[super layoutSubviews];
//_min --value-- _max
//(value - _min)/(_max - _min)
_tView.frame = CGRectMake(0, 0, (_value - _minimumValue)/(_maximumValue - _minimumValue) * self.frame.size.width, self.frame.size.height);
}
@end