如何封装一个自定义的UISlider

#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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值