I have a UISlider
(min 1 ,max 10). I want its thumb to have a UILabel
placed on top of it that continuously updates and changes its text on moving the UISlider
's thumb. So, I grabbed thumb image from the UISlider
and added a UILabel
to it but the label seems to overwrite itself without erasing the previous value once the thumb is moved.
- (IBAction)SnoozeSliderValueChanged:(id)sender {
UIImageView *handleView = [_snoozeSlider.subviews lastObject];
UILabel *label = [[UILabel alloc] initWithFrame:handleView.bounds];
label.text = [NSString stringWithFormat:@"%0.0f", self.snoozeSlider.value];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = NSTextAlignmentCenter;
[handleView addSubview:label];
}
Initially,
Then, when i start dragging,
I want the label to erase the previous value and show current value as the thumb is moved. Any help is appreciated.Thanks!
I've created a Swift Class for similar purpose. Its name is MBSliderView
It can be used both in storyboard and from code.
It has 2 display modes for displaying current slider value.
In normal state, it shows value inside thumb like this:
And when thumb is pressed, it displays the current value like this:
From code it can be used like this:
and in order to receive the slider value, you must implement the
MBSliderDelegate
. Something like this:Here is the complete sample code.
I know its very to late to answer, but hope this helps you or someone else
Your code continuously adds new subviews. Remove the existing subviews with:
Alternatively, reuse the existing label. Perhaps using a tag and
viewWithTag:
to find the existing label and update (or create if not found). Reuse is more efficient than recreation.This is because, on each slider value changed event, you are creating new
UILabel
instance and adding this to view. You can just create theUILabel
once and on subsequent calls, just update the label frame and label text like below: