Search code examples
iphoneuislider

UISlider Change values in iPhone


I have 4 values in UISlider. I want that when the slider value changes it should display the following values

  if (slider.value==0)
  {
      label.text="5";
  }
  else if(slider.value==1)
  {
      label.text="10"
  }
  else
  {
      label.text="15";
  }

Solution

  • You need to create a connection to the UISlider's Value Changed event in Interface Builder. You can implement a method such as:

    - (IBAction)sliderValueChanged:(UISlider *)slider {
        if (slider.value < 1) {
            self.label.text = @"5";
        }
        else if (slider.value < 2) {
            self.label.text = @"10";
        }
        else {
            self.label.text = @"15";
        }
    }
    

    If you want to hook up the event programatically, you can use:

    [self.mySlider addTarget:self action:@selector(sliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    

    Note that the slider will be reporting values with decimal places, so your cases where the value equals an integer are rare. Change the logic to use less-than checks as shown above.