Custom UISlider - Increase “hot spot” size

2019-01-17 04:50发布

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];

7条回答
Lonely孤独者°
2楼-- · 2019-01-17 05:13

Swift 3

Subclass of UISlider with increased touch area

class CustomSlider: UISlider {

    private var thumbTouchSize = CGSize(width: 40, height: 40)

    override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
        let increasedBounds = bounds.insetBy(dx: -thumbTouchSize.width, dy: -thumbTouchSize.height)
        let containsPoint = increasedBounds.contains(point)
        return containsPoint
    }

    override func beginTracking(_ touch: UITouch, with event: UIEvent?) -> Bool {
        let percentage = CGFloat((value - minimumValue) / (maximumValue - minimumValue))
        let thumbSizeHeight = thumbRect(forBounds: bounds, trackRect:trackRect(forBounds: bounds), value:0).size.height
        let thumbPosition = thumbSizeHeight + (percentage * (bounds.size.width - (2 * thumbSizeHeight)))
        let touchLocation = touch.location(in: self)
        return touchLocation.x <= (thumbPosition + thumbTouchSize.width) && touchLocation.x >= (thumbPosition - thumbTouchSize.width)
    }
}
查看更多
登录 后发表回答