motox motox - 4 months ago 33
iOS Question

Continuously change value of UILabel on thumb image of UISlider

I have a

(min 1 ,max 10). I want its thumb to have a
placed on top of it that continuously updates and changes its text on moving the
's thumb. So, I grabbed thumb image from the
and added a
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];



enter image description here

Then, when i start dragging,

enter image description here

I want the label to erase the previous value and show current value as the thumb is moved. Any help is appreciated.Thanks!


Your code continuously adds new subviews. Remove the existing subviews with:

[handleView.subviews makeObjectsPerformSelector:@(removeFromSuperview)];

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.