UILabel Over UISlider Thumb

The "knob" isn't available per public API, so bad chances for hooking it up - if it is a subview at all and not just drawn directly.

So you should add you label to the same view as the slider (make sure you add it later so that appears over it). You can then listen for the value change events and place your label accordingly. It is linear scaling between the endpoints that you need to figure out at first, but it shouldn't be too difficult.

Edit with code:

yourLabel = [[UILabel alloc]initWithFrame:....];
// .. configure label
[[yourSlider superview] addSubview:yourLabel];
[yourSlider addTarget:self action:@selector(adjustLabelForSlider:) forControlEvents:UIControlEventValueChanged];


-(void)adjustLabelForSlider:(id)slider
{
    float value = slider.value;
    float min = slider.minimumValue;
    float max = slider.maximumValue;

    CGFloat newX = ...; // Calculate based on yourSlider.frame and value, min, and max
    CGFloat newY = ...;

    [yourLabel setCenter:CGPointMake(newX,newY)];
}

Note: untested code ;-)


Try this

yourLabel = [[UILabel alloc]initWithFrame:....];

//Call this method on Slider value change event

-(void)sliderValueChanged{
    CGRect trackRect = [self.slider trackRectForBounds:self.slider.bounds];
    CGRect thumbRect = [self.slider thumbRectForBounds:self.slider.bounds
                               trackRect:trackRect
                                   value:self.slider.value];

    yourLabel.center = CGPointMake(thumbRect.origin.x + self.slider.frame.origin.x,  self.slider.frame.origin.y - 20);
}

I could get most accurate value by using this snippet.


Same answer with swift3:

    let trackRect: CGRect  = slider.trackRect(forBounds: slider.bounds)
    let thumbRect: CGRect  = slider.thumbRect(forBounds: slider.bounds , trackRect: trackRect, value: slider.value)
    let x = thumbRect.origin.x + slider.frame.origin.x
    let y = slider.frame.origin.y - 20
    sliderLabel.center = CGPoint(x: x, y: y)

Tags:

Objective C