40

I found the code below in the Apple documentation and added it to my viewDidLoad method but the slider doesn't appear when I run the code.

CGRect frame = CGRectMake(0.0, 0.0, 200.0, 10.0);
UISlider *slider = [[UISlider alloc] initWithFrame:frame];
[slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
[slider setBackgroundColor:[UIColor clearColor]];
slider.minimumValue = 0.0;
slider.maximumValue = 50.0;
slider.continuous = YES;
slider.value = 25.0;
tshepang
  • 12,111
  • 21
  • 91
  • 136
Christian Gossain
  • 5,942
  • 12
  • 53
  • 85

3 Answers3

25

You need to add the slider into your view hierarchy. Add [self.view addSubview:slider]; and it should work.

Michal
  • 4,846
  • 3
  • 33
  • 25
23

Try this Code:

Create a new slider

-(IBAction)mySlider
{ 
    CGRect frame = CGRectMake(0.0, 0.0, 200.0, 10.0);
    UISlider *slider = [[UISlider alloc] initWithFrame:frame];
    [slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [slider setBackgroundColor:[UIColor clearColor]];
    slider.minimumValue = 0.0;
    slider.maximumValue = 50.0;
    slider.continuous = YES;
    slider.value = 25.0;
    [self.view addSubview:slider];
}

Slider Actions

-(void)sliderAction:(id)sender
{
    UISlider *slider = (UISlider*)sender;
    float value = slider.value;
    //-- Do further actions
}
Rajesh Loganathan
  • 11,129
  • 4
  • 78
  • 90
  • 1
    To access the slider value, use the UISlider property called "value". Please edit your answer. It crashes as written. – jbcaveman Mar 06 '14 at 07:04
0

Adding to the view via [self.view addSubview:slider] AS PREVIOUS MENTIONED - is essential.

wasn't visible FOR ME at : CGRect frame = CGRectMake(0.0, 0.0, 200.0, 10.0);

You should probably drop it down a bit and maybe get it off the left margin.

perhaps? CGRect frame = CGRectMake(5.0, 10.0, 200.0, 10.0);

For ios 6 and later you should really add this to view did load as well (so you can see it - even if you lowered the frame)

  if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_6_1)
  {
      self.edgesForExtendedLayout=NO;
  }
DontKnow
  • 399
  • 4
  • 14