Sunday, July 6, 2014

iOS Tutorial - Part 13 - Tip Calculator App, UISlider

Tip Calculator

 

Video Description 
Here are the code for the application that is described in this video with bunch of comments.
#import "ViewController.h"

@interface ViewController ()
{
    int tipPercentage;
}
@property (weak, nonatomic) IBOutlet UITextField *totalField;
@property (weak, nonatomic) IBOutlet UILabel *tipPercentageLabel;
@property (weak, nonatomic) IBOutlet UISlider *tipPercentageSlider;
@property (weak, nonatomic) IBOutlet UILabel *resultLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipAmountLabel;

@end

@implementation ViewController

- (IBAction)calculatePressed {
    [self updateResult];
}

- (IBAction)tipPercentageChanged {
    self.tipPercentageLabel.text = [NSString stringWithFormat:@"Tip Percentage %d%%", tipPercentage];
    [self updateResult];
}

- (void)updateResult
{
    //Get the value of the slider
    tipPercentage = self.tipPercentageSlider.value;
    //Convert the totalField text filed into the float value and assign it to a float local variable
    float billAmount = [self.totalField.text floatValue];
    //Calculate the tip amount 
    float tipAmount = tipPercentage * billAmount / 100;
    //Calculate the total bill amount
    float totalBill = billAmount + tipAmount;
    //Wrap the totalBill with NSNumber in order to get the string value of float variable
    NSNumber *totalBillWrapper = [NSNumber numberWithFloat:totalBill];
    //Wrap the tipAmount with NSNumber in order to get the string value of float variable
    NSNumber *tipAmountWrapper = [NSNumber numberWithFloat:tipAmount];
    //Set the value of labels
    self.tipAmountLabel.text = [NSString stringWithFormat:@"Tip amount: %@",[tipAmountWrapper stringValue]];
    self.resultLabel.text = [NSString stringWithFormat:@"Total: %@",[totalBillWrapper stringValue]];
}

@end

Download

Download the Tip Calculator App from here

2 comments:

  1. Hi,

    Why should we use self here?
     tipPercentage = self.tipPercentageSlider.value;

    I am a beginner. Please explain as i am able to execute the program without self also?

    ReplyDelete
    Replies
    1. Hello,
      In objective C in order to use properties or call a function inside of a class you need to add self at the beginning. It's weird that it works without self. Maybe in new version they don't force user to put self. I have to double check.

      Delete