最近在項目中需要一個帶有標(biāo)線的slider驯妄,并且滑塊滑動后停止在標(biāo)線位置荷并。所以自己寫了一個。
下面是代碼青扔,僅供參考源织。
自定義view 的頭文件如下
@interface TSlider: UISlider
@end
@interface LTSliderView : UIView
@property (nonatomic,strong) UIColor *lineColor; // 默認(rèn)黑色
@property (nonatomic,assign) CGFloat lineHeight;
@property (nonatomic,strong) TSlider *t_slider;
@end
自定義view 的實現(xiàn)文件如下
#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];
- 當(dāng)然還有很多熟悉你可以寫到自定義的頭文件中,以便用戶修改赎懦。
- 還有一個需要注意的就是在valueChange的方法中如果你要給label 賦值的話選擇異步雀鹃。
有需要的可以了解一下。
---來自濤胖子的工作筆記