Ken Chan
Ken Chan

Reputation: 115

iOS UILabel position is reset when setText is called

I am now implementing a function in iOS using objective-C, that is making a text label above the "node" of the slider, when the slider value is changing. The text label text is the current value of the slider.

So, I have added the UILabel on the storyboard view controller.

@property (strong, nonatomic) IBOutlet UILabel *tempoSliderLabel;

In the slider onchange function, after calcuating the sliderNodePosition,

[self.tempoSliderLabel setText:[NSString stringWithFormat:@"%ld", sliderTempoValue]];
[self.tempoSliderLabel setCenter: CGPointMake(slideNodePosition.x, slideNodePosition.y - 10.0)];

However, I don't know why the label sometimes return to its original position as in the storyboard. It looks like "flashing" during testing:

Screenshot GIF

Then, I tried again with setText removed, the label is "moving" as expected.

So, how can I prevent setText to reset the label position?

Upvotes: 2

Views: 241

Answers (1)

Shrikant Tanwade
Shrikant Tanwade

Reputation: 1441

IBOutlet of lblValue and it's x constraints like

IBOutlet UILabel * lblValue;
IBOutlet NSLayoutConstraint *sliderValueXconstraints;

enter image description here

IBAction of slider

-(IBAction)sliderAction:(UISlider*)slider
{
    float x = [self xPositionFromSliderValue:slider];
    sliderValueXconstraints.constant=x;
    lblValue.text = [NSString stringWithFormat:@"%f", slider.value];
}

- (float)xPositionFromSliderValue:(UISlider *)aSlider
{
    float sliderRange = aSlider.frame.size.width - aSlider.currentThumbImage.size.width;
    float sliderOrigin = aSlider.frame.origin.x + (aSlider.currentThumbImage.size.width / 2.0);

    float sliderValueToPixels = (((aSlider.value - aSlider.minimumValue)/(aSlider.maximumValue - aSlider.minimumValue)) * sliderRange) + sliderOrigin;

    return sliderValueToPixels;
 }

Output

enter image description here

Upvotes: 2

Related Questions