Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #import "BMICalculatorViewController.h"
- @interface BMICalculatorViewController ()
- @property (weak, nonatomic) IBOutlet UITextField *height_TextField;
- @property (weak, nonatomic) IBOutlet UITextField *weight_TextField;
- @property (weak, nonatomic) IBOutlet UILabel *resultLabel;
- - (IBAction)calculateBMI:(id)sender;
- @end
- @implementation BMICalculatorViewController
- - (void)viewDidLoad
- {
- [super viewDidLoad];
- // Do any additional setup after loading the view, typically from a nib.
- // Gesture for tap anywhere to dissmiss keyboard.
- UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(dismissKeyboard)];
- [self.view addGestureRecognizer:tap];
- }
- - (void)didReceiveMemoryWarning
- {
- [super didReceiveMemoryWarning];
- // Dispose of any resources that can be recreated.
- }
- - (void)dismissKeyboard
- { // Method for tap anywhere to dismiss keyboard
- [_height_TextField resignFirstResponder];
- [_weight_TextField resignFirstResponder];
- }
- - (IBAction)calculateBMI:(id)sender {
- // BMI formula: BMI = ( Weight(Kg) / ( Height(M) x Height(M) ) )
- double height = [self.height_TextField.text doubleValue];
- double weight = [self.weight_TextField.text doubleValue];
- NSString *bmi = [NSString stringWithFormat:@"%.2lf", (weight/(height*height))];
- NSString *resultString = [NSString stringWithFormat:@"Your BMI is:\n%@", bmi];
- // Declaring UIAlertView *resultAlert
- UIAlertView *resultAlert = [[UIAlertView alloc] initWithTitle:@"Invalid"
- message:nil
- delegate:self
- cancelButtonTitle:@"Okay"
- otherButtonTitles:nil];
- if ([self.weight_TextField.text length] == 0 && [self.height_TextField.text length] == 0)
- {
- resultString = @"Please fill in your Height and Weight!";
- resultAlert.message = resultString; // Update resultString with error message.
- [resultAlert show];
- }
- else if ([self.height_TextField.text length] == 0)
- {
- resultString = @"Please fill in your Height!";
- resultAlert.message = resultString;
- [resultAlert show];
- }
- else if ([self.weight_TextField.text length] == 0)
- {
- resultString = @"Please fill in your Weight!";
- resultAlert.message = resultString;
- [resultAlert show];
- }
- else
- {
- self.resultLabel.text = resultString;
- // Clear text fields after results are showned.
- self.height_TextField.text = nil;
- self.weight_TextField.text = nil;
- }
- }
- - (BOOL)textFieldShouldReturn:(UITextField *)textField
- {
- [textField resignFirstResponder];
- return YES;
- }
- - (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
- {
- }
- @end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement