How do I place a slider value in label?

2019-06-03 23:25发布

问题:

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!

回答1:

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];
    }

}


回答2:

Here would be my process to figure out the root cause of this problem.

  1. Did you remember to connect the slider and sliderLabel outlets?
  2. Did you remember to connect the IBAction to the slider? Set a breakpoint. When you drag the slider, does sliderValue: get called? What are the values of slider and sliderLabel?
  3. Its unusual that your IBOutlets are not properties. I would expect to see:

@property (weak, nonatomic) IBOutlet UISlider *slider; and

@property (weak, nonatomic) IBOutlet UILabel *sliderLabel;



回答3:

I tried your code and seems to be correct..Please check these things:-

1) Have you connected Slider action Value Changed to IBAction method for proper functioning.

2) Check our connections with Outlets.

Hope helps you out..