带有标线的UISlider

最近在项目中需要一个带有标线的slider,并且滑块滑动后停止在标线位置。所以自己写了一个。
下面是代码,仅供参考。

自定义view 的头文件如下

@interface TSlider: UISlider

@end

@interface LTSliderView : UIView
@property (nonatomic,strong) UIColor *lineColor; // 默认黑色
@property (nonatomic,assign) CGFloat lineHeight;
@property (nonatomic,strong) TSlider *t_slider;  
@end

自定义view 的实现文件如下

#define TRACK_HEIGHT 3.0
#import "LTSliderView.h"

@implementation TSlider

-(CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value{
    
    rect.origin.x=rect.origin.x-15;
    rect.size.width=rect.size.width+30;
    return CGRectInset([super thumbRectForBounds:bounds trackRect:rect value:value],15,15);
}

-(CGRect)trackRectForBounds:(CGRect)bounds{
    
    bounds.origin.x=0;
//    bounds.origin.y=bounds.origin.y;
    bounds.origin.y=bounds.origin.y + bounds.size.height - TRACK_HEIGHT;
    bounds.size.height = TRACK_HEIGHT;
    bounds.size.width=bounds.size.width;
    return bounds;
}

@end

@implementation LTSliderView

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self){
        self.lineHeight = 30;
        self.lineColor = [UIColor blackColor];
        [self createSliderWithFrame:frame];
    }
    return self;
}

- (void)createSliderWithFrame:(CGRect)frame{
    
    self.t_slider = [[TSlider alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
    self.t_slider.minimumValue = 0;
    self.t_slider.maximumValue = 10;
    
    [self addSubview:self.t_slider];
    for (int i = 0; i < 11; i++) {
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(i*self.t_slider.bounds.size.width/10, 0, 1, frame.size.height - TRACK_HEIGHT)];
        label.backgroundColor = self.lineColor;
        [self addSubview:label];
    }
    [self bringSubviewToFront:self.t_slider];
}

- (void)setLineColor:(UIColor *)lineColor{
    _lineColor = lineColor;
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[UILabel class]]){
            subView.backgroundColor = lineColor;
        }
    }
}
- (void)setLineHeight:(CGFloat)lineHeight{
    _lineHeight = lineHeight;
    for (UIView *subView in self.subviews) {
        if ([subView isKindOfClass:[UILabel class]]){
            CGRect rect = subView.frame;
            rect.origin.y = self.t_slider.bounds.size.height - lineHeight-TRACK_HEIGHT;
            rect.size.height = lineHeight;
            subView.frame = rect;
        }
    }
}

自定义view 的使用如下:

    self.t_slider = [[LTSliderView alloc] initWithFrame:CGRectMake(40, 300, [UIScreen mainScreen].bounds.size.width-80, 50)];
    self.t_slider.lineColor = [UIColor redColor];
    self.t_slider.lineHeight = 10.f;
    [self.t_slider.t_slider addTarget:self action:@selector(valueChange:) forControlEvents:UIControlEventValueChanged];
    [self.view addSubview:self.t_slider];
  • 当然还有很多熟悉你可以写到自定义的头文件中,以便用户修改。
  • 还有一个需要注意的就是在valueChange的方法中如果你要给label 赋值的话选择异步。

有需要的可以了解一下。

---来自涛胖子的工作笔记

你可能感兴趣的:(带有标线的UISlider)