Coming from Java & Android development and Objective-C still is a bit strange to me, but I just went in head first and started writing code. Before I started getting really far into it, I just want to throw some basic code here for suggestions about correct syntax, etc. I just want to make sure that my variable and function declarations are correct as well as the way I refer to UI elements is the recommended method.
So I was told to make a separate ViewController class for each UI I build as below:
@interface CalculatorViewController : UITableViewController
@property (weak, nonatomic) IBOutlet UITextField *fatTextField;
@property (weak, nonatomic) IBOutlet UITextField *carbsTextField;
@property (weak, nonatomic) IBOutlet UITextField *fiberTextField;
@property (weak, nonatomic) IBOutlet UITextField *proteinTextField;
@property (weak, nonatomic) IBOutlet UITextField *servingsTextField;
@property (weak, nonatomic) IBOutlet UITextField *foodnameTextField;
@property (weak, nonatomic) IBOutlet UILabel *pointsLabel;
- (IBAction)calculate:(id)sender;
- (IBAction)reset:(id)sender;
- (IBAction)addtotracker:(id)sender;
- (void)resetCalculator;
- (void)calculatePoints;
Then inside the CalculatorViewController.m file I ended up with the following code snippets.
// UI FUNCTIONS
- (void) resetCalculator {
// Reset all nutrion fact fields.
_fatTextField.text = @"";
_carbsTextField.text = @"";
_fiberTextField.text = @"";
_proteinTextField.text = @"";
_servingsTextField.text = @"";
// Reset food name & points label
_foodnameTextField.text = @"";
_pointsLabel.text = @"Points: 0";
// Set Fat as firstresponder
[self.fatTextField becomeFirstResponder];
}
- (void) calculatePoints {
float fatFloat = [_fatTextField.text floatValue];
float carbsFloat = [_carbsTextField.text floatValue];
float fiberFloat = [_fiberTextField.text floatValue];
float proteinFloat = [_proteinTextField.text floatValue];
float servingsFloat = [_servingsTextField.text floatValue];
float points = proteinFloat + carbsFloat + fatFloat - fiberFloat;
points = points / 100;
points = roundf(points);
points = MAX(points, 0);
_pointsLabel.text = [NSString stringWithFormat:@"Points: %f", points];
}
- (IBAction)calculate:(id)sender {
NSLog(@"Calculate button pressed!");
// Close the keyboard
[self.view endEditing:YES];
}
- (IBAction)reset:(id)sender {
NSLog(@"Reset button pressed!");
[self resetCalculator];
}
- (IBAction)addtotracker:(id)sender {
NSLog(@"Tracker button pressed!");
}