Search code examples
uiviewdrag-and-dropuigesturerecognizeruislideruipangesturerecognizer

UIGestureRecognizer to make UISlider from scratch


Hy,

I'm trying to implement a custom UISlider from scratch based on UIGestureRecognizer because I have to make the thumb view a custom one with a clean design. The UIGestureRecognizer usage is a request from technical lead.

What I have until now it's a sample where I made tests:

func setupSlider() {        
    let panGesture = UIPanGestureRecognizer(target: self, action: #selector(dragged(gestureRecognizer:)))
    sliderView.isUserInteractionEnabled = true
    sliderView.addGestureRecognizer(panGesture)
}

@objc func dragged(gestureRecognizer: UIPanGestureRecognizer) {
    if gestureRecognizer.state == UIGestureRecognizer.State.began || gestureRecognizer.state == UIGestureRecognizer.State.changed {
        let translation = gestureRecognizer.translation(in: self.sliderContainer)
        gestureRecognizer.view!.center = CGPoint(x: gestureRecognizer.view!.center.x + translation.x, y: gestureRecognizer.view!.center.y + translation.y)
        gestureRecognizer.setTranslation(CGPoint(x: 0, y: 0), in: self.view)
    }
}

In this point I have twoproblems:

  1. to keep the slider view in the middle of container
  2. to be able to get "curent value" of the slider based on the min and max value of the interval

Can you help with any suggestion, please ?

Kind regards.


Solution

  • Not technically an answer to your question but....

    I'm trying to implement a custom UISlider from scratch based on UIGestureRecognizer because I have to make the thumb view a custom one with a clean design.

    Are you aware that you can customize the thumb image?

    See for example this article: https://zeitschlag.net/customizing-uislider/
    This is the API: setThumbImage(_:for:)

    The UIGestureRecognizer usage is a request from technical lead.

    If you can manage to get the result by using UISlider after all, I am sure your lead will welcome it.