首先說下為什么要自定義Slider
UISlider系統(tǒng)提供的方法:
- (void)setThumbImage:(UIImage *)image forState:(UIControlState)state;
- (void)setMinimumTrackImage:(UIImage *)image forState:(UIControlState)state;
- (void)setMaximumTrackImage:(UIImage *)image forState:(UIControlState)state;
只能更改3種背景圖片虱饿。如果設(shè)計要做成這樣...基本就可以放棄使用UISlider了
基本思路
創(chuàng)建UIimageView? * linBgImageView ? ? ? ?slide未被選中的背景?
創(chuàng)建UIView? ? ? ? ? * linView ? ? ? ? ? ? ? ? ? ? ? slide選中的背景?
創(chuàng)建UIImageView * linBgPointImageView? slide上面的刻度
創(chuàng)建UIImageView * touchImageView ? ? ? ? slide上面拖動的點
實現(xiàn)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下,謝謝)