Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 560
motox Avatar asked Dec 16 '22 00:12

motox


1 Answers

    - (IBAction)SnoozeSliderValueChanged:(id)sender {

        //Get the Image View
        UIImageView *handleView = [_snoozeSlider.subviews lastObject];

        // Get the Slider value label
        UILabel *label = (UILabel*)[handleView viewWithTag:1000];

        // If the slider label not exist then create it and add it to the Handleview. So handle view will have only one slider value label, so no more memory issues & not needed to remove from superview.
        // Creation of object is Pain to iOS. So simply reuse it by creating only once.
        // Note that tag setting below, which will helpful to find out that view presents in later case
        if (label==nil) {

            label = [[UILabel alloc] initWithFrame:handleView.bounds];

            label.tag = 1000;

            label.backgroundColor = [UIColor clearColor];

            label.textAlignment = NSTextAlignmentCenter;

            [handleView addSubview:label];


        }

        // Update the slider value
        label.text = [NSString stringWithFormat:@"%0.0f", self.snoozeSlider.value];

    }
like image 59
Vijay-Apple-Dev.blogspot.com Avatar answered Mar 15 '23 22:03

Vijay-Apple-Dev.blogspot.com