iOS controlling a slider value and text label valu

2019-08-31 14:06发布

问题:

I already have a slider that controls the output of a text label.

-(IBAction)mySlider:(UISlider *)sender
{
    _myTextLabel.text = [NSString stringWithFormat:@"%i", (int) sender.value];
}

However, I also want a stepper to be able to changer the slider's position. So, if the slider has been set to 50, and the text label says 50, I want the stepper to increment to 51, 52, 53, etc. Does anyone know the code to do this? Thanks!

回答1:

You will need to keep an reference for the UISlider. Make a handler for UIStepper with valueChanged event.

Some settings that need to be done for both stepper and slider

Set minimum value and maximum value for both stepper and slider as 0 and 100 respectively. Set the step size of stepper as 1. Set the default value same for both stepper ans slider.

- (void)viewDidLoad
{
    [super viewDidLoad];

    self.slider.minimumValue = 0;
    self.slider.maximumValue = 100;

    self.stepper.minimumValue = 0;
    self.stepper.maximumValue = 100;
    self.stepper.stepValue = 1;

    self.slider.value = 10;
    self.stepper.value = 10;

}

- (IBAction)stepperValueChanged:(UIStepper *)sender {

    [self.slider setValue:sender.value];

    self.myTextLabel.text = [@((int)sender.value) stringValue];

}

- (IBAction)sliderValueChanged:(UISlider *)sender {

    [self.stepper setValue:sender.value];

    self.myTextLabel.text = [@((int)sender.value) stringValue];
}