iOS UISlider滑動塊觸摸范圍調整變大


正常情況下,我們自定義的滑動區域都不會太大,否則UI不美觀,但是這樣,又會手勢不靈敏,用戶體驗變差。

如何解決?

 

這里有一種方案:封裝一個繼承UISlider的自定義類,重寫thumbRectForBounds方法,原理就是對thumb區域rect進行放大處理。

 

 

代碼如下:

1、新建一個類,繼承UISlider

h文件:

#import <UIKit/UIKit.h>



@interface DBSlider : UISlider

@end

 

 

m文件:

#import "DBSlider.h"

#define thumbBound_x 10
#define thumbBound_y 20

@interface DBSlider ()
{
    CGRect lastBounds;
}

@end

@implementation DBSlider


- (CGRect)thumbRectForBounds:(CGRect)bounds trackRect:(CGRect)rect value:(float)value
{

    rect.origin.x = rect.origin.x;
    rect.size.width = rect.size.width ;
    CGRect result = [super thumbRectForBounds:bounds trackRect:rect value:value];
    
    lastBounds = result;
    return result;
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event{
    
    UIView *result = [super hitTest:point withEvent:event];

      if (point.x < 0 || point.x > self.bounds.size.width){

        return result;

      }

if ((point.y >= -thumbBound_y) && (point.y < lastBounds.size.height + thumbBound_y)) {
        float value = 0.0;
        value = point.x - self.bounds.origin.x;
        value = value/self.bounds.size.width;
        
        value = value < 0? 0 : value;
        value = value > 1? 1: value;
        
        value = value * (self.maximumValue - self.minimumValue) + self.minimumValue;
        [self setValue:value animated:YES];
    }
    return result;
    
}

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event{
    BOOL result = [super pointInside:point withEvent:event];
    if (!result && point.y > -10) {
        if ((point.x >= lastBounds.origin.x - thumbBound_x) && (point.x <= (lastBounds.origin.x + lastBounds.size.width + thumbBound_x)) && (point.y < (lastBounds.size.height + thumbBound_y))) {
            result = YES;
        }
      
    }
      return result;
}

@end

 

代碼直接拷貝即可。

 

如果你已經用UISlider畫好了控件:

1、如果是代碼創建,直接更改類名-UISlider  ->  DBSlider

2、如果是xib,修改控件的Custom Class, 再重新連線就可以了,其他都不用改。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM