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, 再重新连线就可以了,其他都不用改。

 

posted @ 2017-04-17 11:58  那一抹风情  阅读(8620)  评论(0编辑  收藏  举报