Using an array of strings for UISlider - iphone

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)

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];

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;
}

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];

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)];
}

Related

Display Random String from a Selection?

I'm just palying around with Xcode (I'd like to start making iPhone apps) and I was wondering how you would make this progress HUD randomly show strings? Currently:
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
hud.labelText = #"Give me a sec...";
}
So I'd like it to randomly choose from things like, 'Give me a sec', 'Hold on', etc. Just something I'd like to learn, thanks for any help!
I tried searching around but it's very hard to think of appropiate search terms!
Put all your strings in an array, get a random number between 0 and size of array (minus 1), and use that to retrieve the msg. Put in method to make it easy. Define the msg array outside though, for better code.
Something similar to this:
-(NSString*) getRandomMsg {
NSArray *arr = #[#"Give me a sec", #"Hold on"];
int randNum = arc4random_uniform([arr count]); // or arc4random, possibly rand % max
NSString *msg = arr[randNum];
return msg;
}

NSNumber stores zero value instead of the correct numeric value

I developing a simple calculator iPhone application. Just for practicing purpose. I have an IBAction method that stores the digits that the user entered. The whole concept is that the calculator app piles up pending oprations so the user can perform multiple actions and the screen shows the result the following way: 1 + 2 - 4 + 10 = X. So i have two NSMutableArray that stores NSNumber numbers and the operator actions. When the user clicks an operator button, a new array element created for the new number. When the users entering the digits, the last array element is updating itself until an operator button is pressed.
The problem is that every array element is zero. Inside the method it stores the corrent value when i set it, but when the method is executed and called again it contins nothing but zeros instead of the entered numbers. The NSNumber objects are present, the array contains every number, but every number is 0.
Here is the method:
// Processing digit buttons
- (IBAction)clickDigit: (UIButton *) sender {
double currentNumber = [[numbers lastObject] doubleValue];
// Get the digit
double digit = sender.tag;
// Do nothing when the currentNumber and the digit both zero
if(currentNumber == 0 && digit == 0) {
return;
}
// When currentNumber is zero, override the value
if(currentNumber == 0) {
currentNumber = digit;
[numbers removeLastObject];
[numbers addObject: [NSNumber numberWithDouble: currentNumber ]];
// Else, add the digit to currentNumber
} else {
currentNumber = currentNumber * 10 + digit;
[numbers removeLastObject];
[numbers addObject: [NSNumber numberWithDouble: currentNumber ]];
}
// Update the screen
[self updateDisplay];
}
I have no clue what's wrong. Any suggestions?
Thanks in advance
UPDATE: it turns out that the clickClear method is automatically called after each button press. It sets the value zero. I linked the full source code below this post in the comment section. The only question is: why this method called? What calls this method?
UPDATE2: with The Saad's help i managed to solve this problem. Thanks to everyone! :)
The only possible way you get this problem is if sender.tag == 0 all the time. So you should definitely check that. My point here is that there is not other possible scenario that produces those symptoms, so it has to be it.
ok got it,
one thing here is that first check your sender's tag, either by braekpoint or by NSLog in click Digit method, i guess tags never gets up than zero, and hence the last object in array will always be zero, further, place nslog or breakpoint on all places where you are adding object to array.
in interface.
#property(nonatomic, retain) NSMutableArray* numberArray;
in implementation,
#synthesize numberArray = _numberArray;
in dealloc
[_numberArray release];
ok now next thing is to make an array in init which is
NSMutableArray* arr = [NSMutableArray alloc] init];
self.numberArray = arr;
[arr release];
[self.numberArray addObject:[NSNumber numberWithDouble:0]];

Add numerical content of UITextFields

I have four separate UITextFields and I want to add the numerical value of them all and then display the content within a UILabel, below is current code:
- (void)updateString {
self.string1 = textField1.text;
self.string2 = textField2.text;
self.string3 = textField3.text;
self.string4 = textField4.text;
self.string5 = textField5.text;
label.text = self.total; // total is an NSString and label is a UILabel
}
I am unable to add together the numerical values within each textField1/2/3... and store the value within total and then update the label. Any suggestions?
NSString has a method on it -intValue. That is what you want to use.
Check the section "Getting Numeric Values" in the NSString documentation
int totalValue = [textField1.text intValue] + [textField2.text intValue]...;
label.text = [NSString stringWithFormat:#"The total value is %d", totalValue];

How do I program a slider to do two things with one button?

Basicly, I'm making an app that lets you add or subtract by a certain number and I want to do so with a slider. How would I program a slider to be able to add or subtract by an integer by tapping a different button for adding and subtracting. For example, say you want to add by 3. You slide the bar to three then tap the "+" to add three. How would I program this?
EDIT: This is the code that I want to implement it in:
int number = 0
-(IBAction)IncrementNumber:(id)sender {
number++;
[currentNumber setText:[NSString stringWithFormat:#"%d", number]];
}
-(IBAction)DecrementNumber:(id)sender {
number--;
[currentNumber setText:[NSString stringWithFormat:#"%d", number]];
}
#synthesize MySlider, MyTextField;
-(IBAction) sliderValueChanged:(UISlider *)sender {
MyTextField.text = [NSString stringWithFormat:#" %1.0f", [sender value]];
}
-(IBAction) changeButtonPressed:(id)sender {
NSString *textValue = [MyTextField text];
float value = [textValue floatValue];
if (value < 0) value = 1;
if (value > 100) value = 100;
MySlider.value = value;
MyTextField.text = [NSString stringWithFormat:#"%1.0f", value];
if ([MyTextField canResignFirstResponder]) [MyTextField resignFirstResponder];
}
-(void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {
if (MyTextField) {
if ([MyTextField canResignFirstResponder]) [MyTextField resignFirstResponder];
}
You could bind the slider to some variable, and the two buttons, [+] and [-] to two functions, say add and sub.
When the functions are called, they grab the value from the variable, and add / subtract it to / from something.
In your edit, assuming that sliderValueChanged is called when the slider value is changed, that function should alter number, so that IncrementNumber and DecrementNumber can have the updated value.
What should work is to define number as IBOutlet in your header file (.h). Then, in interface builder, you can bind the value of the slider to number. This way, whenever you change de slider, the number variable changes accordingly.
In the interface, declare two functions that will be bound to the [+] and [-] boutons:
IBOutlet int number;
-(IBAction) add: (id) sender;
-(IBAction) sub: (id) sender;
In the definition of those functions, you take whatever number you want to change and add to it the number variable that you declared earlier.
Something like the following should do the trick, if value has the number you want to modify:
-(IBAction) add: (id) sender {
value += number;
}
-(IBAction) sub: (id) sender {
value -= number;
}
You could of course combine the two functions into one, and decide wether you should add or subtract according to which button was pressed (you get that by looking into the sender argument) but I think it's less effective, and the code woud be more complex for no reason.
By using slider control u can set the value of that operands by it`s valueChanged event.After Setting value you can perform operation (+/-). for more help on slider you can find data here

Retrieve NSNumber From Array

I am relatively new to Objective C and need some array help.
I have a plist which contains a Dictionary and an NSNumber Array, with more arrays to
be added later on.
NSMutableDictionary *mainArray = [[NSMutableDictionary alloc]initWithContentsOfFile:filePath];
NSArray *scoresArray = [mainArray objectForKey:#"scores"];
I need to retrieve all the values from the array and connect them to 10 UILabels which
I've set up in interface builder. I've done the following to cast the NSNumber to a String.
NSNumber *numberOne = [scoresArray objectAtIndex:0];
NSUInteger intOne = [numberOne intValue];
NSString *stringOne = [NSString stringWithFormat:#"%d",intOne];
scoreLabel1.text = stringOne;
This seems a very long winded approach, I'd have to repeat the 4 lines above ten times to retrieve all the array values. Could I use a for loop to iterate through the array with all of the values converted to Strings at the output?
Any info would be greatly appreciated.
// create NSMutableArray* of score UILabel items, called "scoreLabels"
NSMutableArray *scoreLabels = [NSMutableArray arrayWithCapacity:10];
[scoreLabels addObject:scoreLabel1];
[scoreLabels addObject:scoreLabel2];
// ...
NSUInteger _index = 0;
for (NSNumber *_number in scoresArray) {
UILabel *_label = [scoreLabels objectAtIndex:_index];
_label.text = [NSString stringWithFormat:#"%d", [_number intValue]];
_index++;
}
EDIT
I'm not sure why you'd want to comment out _index++. I haven't tested this code, so maybe I'm missing something somewhere. But I don't see anything wrong with _index++ — that's a pretty standard way to increment a counter.
As an alternative to creating the scoreLabels array, you could indeed retrieve the tag property of the subviews of the view controller (in this case, UILabel instances that you add a tag value to in Interface Builder).
Assuming that the tag value is predictable — e.g., each UILabel from scoreLabel1 through scoreLabel10 is labeled with a tag equal to the values of _index that we use in the for loop (0 through 9) — then you could reference the UILabel directly:
// no need to create the NSMutableArray* scoreLabels here
NSUInteger _index = 0;
for (NSNumber *_number in scoresArray) {
UILabel *_label = (UILabel *)[self.view viewWithTag:_index];
_label.text = [NSString stringWithFormat:#"%d", [_number intValue]];
_index++;
}
The key to making that work is that the tag value has to be unique for the UILabel and must be something you can reference with -viewWithTag:.
The code above very simply assumes that the tag values are the same as the _index values, but that isn't required. (It also assumes the UILabel instances are subviews of the view controller's view property, which will depend on how you set up your interface in Interface Builder.)
Some people write functions that add 1000 or some other integer that allows you group types of subviews together — UILabel instances get 1000, 1001, and so on, and UIButton instances would get 2000, 2001, etc.
try using stringValue...
scoreLabel1.text = [(NSNumber *)[scoresArray objectAtIndex:0] stringValue];