Search code examples
iphoneobjective-cipaduislider

how to load UISlider in iphone application with default initial values and then we can increase


I want that i have 4 values in UISlider and i want that bydefaul values one should be selected when the application is loaded how to make that.

I want that when loaded it shows initial values.

      slider=[[UISlider alloc] initWithFrame:CGRectMake(290, 152, 160, 36)];
      slider.minimumValue=0;
      slider.maximumValue=3;
      [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];

Slider Event

     -(IBAction)sliderAction:(id)sender 
     {
          NSString*testing=[[NSString alloc] initWithFormat:@"%d",(int)slider.value];
          if([testing isEqualToString:@"0"])
          {
              sliderLabel.text=@"5 (gal/acre)";
              sliderValue=@"5";
          }
          else if([testing isEqualToString:@"1"])
          {
              sliderLabel.text=@"10 (gal/acre)";
              sliderValue=@"10";
          }
          else if([testing isEqualToString:@"2"])
          {
              sliderLabel.text=@"15 (gal/acre)";
              sliderValue=@"15";
          }
          else 
          {
              sliderLabel.text=@"20 (gal/acre)";
              sliderValue=@"20";          
          }    
    }

Solution

  • If you need the slider to be able to select the discreet value 0.0, 1.0, 2.0 or 3.0, you may need to handle two of the controller events:

    [slider addTarget:self action:@selector(handleSliderValueChanged:) forControlEvents:UIControlEventValueChanged];
    [slider addTarget:self action:@selector(handleSliderTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    

    The former needs to control the value change and the latter fix the slider pin position after the user will remove his finger.

    To get the discreet slider value we can round it up:

    - (float)roundedSliderValue:(UISlider *)slider
    {
        return roundf([slider value]);
    }
    

    When user is moving the slider we need to get the discreet pin position:

    - (void)handleSliderValueChanged:(UISlider *)slider
    {
        int idx = (int)[self roundedSliderValue:slider];
    
        switch (idx) {
        // update UI
        }
    }
    

    After the use did finish moving the slider we need to correct the pin position and save the value in defaults

    - (void)handleSliderTouchUpInside:(UISlider *)slider
    {
        float val = [self roundedSliderValue:slider]
        [slider setValue:val animated:YES];
        [[NSUserDefaults standardUserDefaults] setFloat:val forKey:@"SliderValue"];
    }
    

    You can use the NSUserDefaults to store the selected value as default and load it on viewDidLoad

    - (void)viewDidLoad
    {
        [super viewDidLoad];
    
        float sliderVal = [[NSUserDefaults standardUserDefaults] floatForKey:@"SliderValue"];
        [self.slider setValue:sliderVal];
    }