Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom UISlider - Increase "hot spot" size

I have a custom UISlider that is relatively tough for big fingered people to grab hold of and slide due to the size of the "thumb image". Is there any way to increase the size of clickable / draggable area without altering the size of the image?

Here's the code I have for creating the custom slider if that helps:

[slider setMaximumTrackImage:[[UIImage imageNamed:@"max.png"]
                                             resizableImageWithCapInsets:UIEdgeInsetsMake(0, 20, 0, 20)]
                                   forState:UIControlStateNormal];
[slider setMinimumTrackImage:[[UIImage imageNamed:@"min.png"]
                                             resizableImageWithCapInsets:UIEdgeInsetsMake(0, 20, 0, 20)]
                                   forState:UIControlStateNormal];
[slider setThumbImage:[UIImage imageNamed:@"thumb.png"]
                            forState:UIControlStateNormal];
like image 381
unsunghero Avatar asked Nov 02 '12 13:11

unsunghero


2 Answers

I ended up subclassing the UISlider and overriding this method:

- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent*)event {
    CGRect bounds = self.bounds;
    bounds = CGRectInset(bounds, -10, -15);
    return CGRectContainsPoint(bounds, point);
}

This extends the touchable area by 10 pixels on the left and right and 15 pixels on the top and bottom.

like image 102
unsunghero Avatar answered Nov 10 '22 16:11

unsunghero


This solution works with iOS 8:

class ExtUISlider: UISlider {

    var thumbTouchSize : CGSize = CGSizeMake(50, 50)

    override func pointInside(point: CGPoint, withEvent event: UIEvent?) -> Bool {
        let bounds = CGRectInset(self.bounds, -thumbTouchSize.width, -thumbTouchSize.height);
        return CGRectContainsPoint(bounds, point);
    }

    override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
        let thumbPercent = (value - minimumValue) / (maximumValue - minimumValue)
        let thumbSize = thumbImageForState(UIControlState.Normal)!.size.height
        let thumbPos = CGFloat(thumbSize) + (CGFloat(thumbPercent) * (CGFloat(bounds.size.width) - (2 * CGFloat(thumbSize))))
        let touchPoint = touch.locationInView(self)

        return (touchPoint.x >= (thumbPos - thumbTouchSize.width) &&
            touchPoint.x <= (thumbPos + thumbTouchSize.width))
    }
}

Credits go to this post: http://www.mpatric.com/2009-04-15-more-responsive-sliders-on-the-iphone

like image 7
Thomas Avatar answered Nov 10 '22 16:11

Thomas