motox motox - 2 months ago 17
iOS Question

Continuously change value of UILabel on thumb image of UISlider

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,

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!

Answer

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.