UISlider Unusual Track Behaviour

I subclassed UISlider and changed the track width (and nothing else) and as you move the slider to the end the last bit of the track appears before the thumb has been moved to the end and there is no radius on the end. If the thumb is at the start you have to move the thumb quite a bit before the track starts to highlight.

  • class CustomSlider: UISlider {

        override func trackRect(forBounds bounds: CGRect) -> CGRect {

            let point = CGPoint(x: bounds.minX, y: bounds.midY)

            return CGRect(origin: point, size: CGSize(width: bounds.width, height: 20))

        }

    }

Add a Comment

Replies

Screenshot is useful but we should also need to see the entire subclass code.

  • Added a comment with the subclass code

Add a Comment

I cannot reproduce. Are you sure you posted the whole code for the class ?

But why do you override trackRect ?

  • Yeah that is the whole subclass. That issue only happens when you move the thumb to the end of the track.

  • I overdid trackRect to increase the track height

  • I think when the track height is at it's default height the thumb usually covers that section of the track so maybe that behaviour is somewhat intentional? I have found one other case with a similar behaviour although that had something to do with the language set being right aligned. Other than that I haven't come across anyone else with this issue. Is there any other way to increase the track height? Im trying to make the slider look like the one in control centre (macOS).

Add a Comment

OK, I see it, but with smaller effect

That's because your subclassing is wrong.

If you try to add an IBAction to the slider, yet is not executed.

To subclass and redraw the slider, you have to do it in:

	override func draw(_ rect: CGRect) {

See examples here:

  • in objc

https://medium.com/@0209neha/creating-a-custom-uislider-7756bf898832

  • or here in swift

https://gist.github.com/Tulakshana/0b903747c20e04a14160882ce51230e3

  • I was following this guide https://medium.com/ios-os-x-development/how-to-personalize-and-use-uislider-in-swift-ec96d2e8f99d

    Those two that you provided edit the thumb in thumbRect and don't mention the track. Looking at them are you saying I have to create another subclass for the track view then use that in trackRect? I noticed that if I set the set the min and max track image I don't get that behaviour however the ends are then both square.

Add a Comment