首先说下为什么要自定义Slider
UISlider系统提供的方法:
- (void)setThumbImage:(UIImage *)image forState:(UIControlState)state;
- (void)setMinimumTrackImage:(UIImage *)image forState:(UIControlState)state;
- (void)setMaximumTrackImage:(UIImage *)image forState:(UIControlState)state;
只能更改3种背景图片。如果设计要做成这样...基本就可以放弃使用UISlider了
基本思路
创建UIimageView * linBgImageView slide未被选中的背景
创建UIView * linView slide选中的背景
创建UIImageView * linBgPointImageView slide上面的刻度
创建UIImageView * touchImageView slide上面拖动的点
实现touchesEnded方法比较麻烦,代码如下:
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
NSInteger allLenght = linBgImageView.frame.size.width;
NSInteger originX = linBgImageView.frame.origin.x+3;
NSInteger unitLenght = (allLenght/12); //7个等级分成12份
//逻辑
// if (touchX <= originX + unitLenght) { //等级0
// touchX = originX + unitLenght * 0;
// }
// else if (touchX <= originX + unitLenght * 3)//等级1
// {
// touchX = originX+unitLenght * 2;
// }
// else if (touchX <= originX + unitLenght * 5)//等级1
// {
// touchX = originX+unitLenght * 4;
// }
for (int i = 0; i < 7; i++) {
NSInteger level = (i*2+1);
if (touchX <= originX + unitLenght * level)//等级1
{
touchX = originX + unitLenght * (level-1);
touchImageView.center = CGPointMake(touchX, linBgImageView.center.y);
[self setvalueLineview];
nowLevel = (((long)level-1)/2)+1;
nowLevelImageView.alpha = 1;
[self performSelectorInBackground:@selector(levelAction) withObject:nil];
return;
}
}
}
- (void)setvalueLineview
{
linView.frame = CGRectMake(linBgImageView.frame.origin.x, linBgImageView.frame.origin.y, touchImageView.center.x-linBgImageView.frame.origin.x, 3);
linView.center = CGPointMake(linView.center.x, linBgImageView.center.y);
}
我又重新整理下代码,可能会有一些不同的地方。但是主要逻辑是一样的。
代码地址:github:https://github.com/YBYHunter/YUSlider (如果喜欢star下,谢谢)