如何封裝一個自定義的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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章