Xcode: Process user input and display answer

Ask for user info, enter info into equation, and display answer.


This will show you how to use Xcode to get two numbers from the user, then multiply those numbers together and display the answer.

After you have learned how to do this, you can use this knowledge to get more than two number and create more complicated equations with ease!

Make two text fields for user inputs
Drag each input to the h file and call it AmountOne and AmountTwo and make sure connection is Outlet and then press connect.

Make Label for answer output
Drag label to h file and call it AnswerLabel and make sure the connection is Outlet and then press connect.

Make button for calculate
Drag label to h file and call it Calculate and make sure the connection is Action and then press connect.

When you are done, the h file should look like this:

#import
@interface ViewController : UIViewController
@property (strong, nonatomic) IBOutlet UITextField *AmountOne;
@property (strong, nonatomic) IBOutlet UITextField *AmountTwo;
@property (strong, nonatomic) IBOutlet UILabel *AnswerLabel;
- (IBAction)Calculate:(id)sender;
@end

Go into the m file and replace this:
- (IBAction)Calculate:(id)sender with this:

- (IBAction)Calculate:(id)sender {

NSString *NumberOneString = [_AmountOne text];
float NumberOneFloat = [NumberOneString floatValue];

NSString *NumberTwoString = [_AmountTwo text];
float NumberTwoFloat = [NumberTwoString floatValue];

float Answer = NumberOneFloat * NumberTwoFloat;

NSString *FinalAnswer = [NSString stringWithFormat:@"Answer: %0.2f", Answer];
[_AnswerLabel setText:FinalAnswer];

[self.view endEditing:TRUE];
}

That's it. Now the user can enter two numbers and you will multiply them together and display the answer. You can change the float Answer above to make a more complicated equation.

You can also add another input by adding another text field and link it to NumberThree and then add these two lines to your h file:

NSString *NumberThreeString = [_AmountThree text];
float NumberThreeFloat = [NumberThreeString floatValue];

You can of course repeat this step many times Four, Five, etc.

FYI: The last line is the last code: [self.view endEditing:TRUE]; is to make the numbers keys go away after the user is done entering information. Delete this line if you want then number keys to stays.



IOS Xcode App Help
Read other useful IOS Apps articles for Xcode developers.













 
 
Copyright  |   Privacy Policy  |   Social Media  |   Disclaimer  |   Directory  |   Contact  |   Advertise  |   Search