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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值