Search code examples
iosxcodeuilabeluislider

How do I place a slider value in label?


I am quite new to Xcode and I am having trouble placing the value of a slider in a label when the slider is value is changed.

Here is my code: Header file:

@interface ViewTwoViewController : UIViewController
{
    IBOutlet UISlider *slider;
    IBOutlet UILabel *sliderLabel;
}

-(IBAction)sliderValue:(id)sender;

and here is my m file:

-(IBAction)sliderValue:(UISlider *)sender {
    sliderLabel.text = [NSString stringWithFormat:@"%g", slider.value];
}

I am not 100% sure why the value isn't updating?

I am looking forward to hearing from you all!


Solution

  • Here's an XCode project that does what you're looking for: http://clrk.it/013r203C1y1F

    Note that:

    1. The label and slider are hooked up to the UIViewController as IBOutlets in the storyboard.
    2. The slider's valueChanged: method is linked to the UIViewController in the storyboard.
    3. The slider's value is displayed using %f.

    Your method would look something like this:

    -(IBAction)sliderValueChanged:(id)sender
    {
        if (sender == _slider) {
            _label.text = [NSString stringWithFormat:@"%0.3f", _slider.value];
        }
    
    }