iOS 使用ScrollView自定義Slider

首先說下為什么要自定義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了

自定義Slider

基本思路

創(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下,謝謝)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容