Adam
Adam

Reputation: 1827

Using an array of strings for UISlider

I want to change a UILabel with strings based on an array. Here is what I have so far:

- (IBAction) sliderValueChanged:(UISlider *)sender {
   scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]];
    NSString *wholeText = @"Very Bad";
    self.scanLabel.text = wholeText;

}

Instead of just "Very Bad," I want different values to show "very Bad, Bad, Okay, Good, Very Good."

Where do I declare the NSMutableArray, and how do I implement it with the slider?

Update: Thank you all for your help! (I love stackoverflow)

Upvotes: 3

Views: 836

Answers (4)

rdelmar
rdelmar

Reputation: 104082

You can implement the array anywhere you want, as long as it's created before you need to use the slider. Sliders can only have a value between 0 and 1 in iOS, so you'll need to multiply the value by something to get numbers as high as the number of items in your array (minus 1), and you'll need to convert them to an integer, so you can use that value as the index into the array. Something like this:

- (IBAction) sliderValueChanged:(UISlider *)sender {
   scanLabel.text = [myArray objectAtIndex:(int)(sender.value * 10)];

}

Upvotes: 1

Anoop Vaidya
Anoop Vaidya

Reputation: 46543

This is not compiler checked...but you may get some idea.

NSArray *texts=[NSArray arrayWithObjects:@"very Bad", @"Bad", @"Okay", @"Good", @"Very Good",nil];
NSInteger sliderValue=[sender value]; //make the slider value in given range integer one.
self.scanLabel.text=[texts objectAtIndex:sliderValue];

Upvotes: 5

foundry
foundry

Reputation: 31745

Put your text values into an array

NSArray* array =  @[@"very Bad", @"Bad", @"Okay", @"Good", @"Very Good"];
  • set your slider to have a min value of 0 and maximum value of 4
  • turn your [sender value] into an int, eg floor([sender value])

pick an item from the array using your int, eg

NSString* result = [array objectAtIndex:myInt];

Upvotes: 1

sqreept
sqreept

Reputation: 5534

You declare it in the same class as the above method.

Let's say it's called wholeTexts.

The code will look like this:

- (IBAction) sliderValueChanged:(UISlider *)sender {
    scanLabel.text = [NSString stringWithFormat:@" %.f", [sender value]];
    NSString *wholeText = [wholeTexts objectAtIndex:(wholeTexts.count - 1) * (int)(sender.value - sender.minimumValue)/(sender.maximumValue - sender.minimumValue)];
    self.scanLabel.text = wholeText;
}

Upvotes: 3

Related Questions