Published on Jun 15,2015
827 Views
Email Post

It’s very common today to find an iphone or ipad in everyone’s hands; people are busy playing with different kinds of apps available while travelling or doing just about any of their daily activities. So as a developer you might wonder why this stuff is so popular and what makes it different from the others. I was in a quest to find out what it was, and got my hands dirty.

The best features making an iphone different are the apps. Apps like face time, Pandora, FlashLight, Instagram, Snapchat, Facebook etc. has made the iOS world so magical that people get totally addicted to it. And the best part, if you actually check out the growth of the number of apps available to the number of apps that is downloaded, you can see a drastic increase in graph.

Graph comparing the number of graph created and number of graph downloaded

Now this was the estimate for the year 2012. If you check the estimate for 2014, you can see that there are 1.2 million apps and about 75 billion downloads i.e the average download per app is 62,500 which is indeed a great number.

By now you must have understood that this is indeed some great stuff and you have got to learn it for sure. Well, in the same mind set, I decided to build my very own first app which converts temperature from Celsius to Fahrenheit and vise versa using a UIPickerView. Today, I will explain in very simple terms how I built mine, so that you’ll understand that it’s actually a cakewalk.

Check your System Configuration

First let me tell you, I have built my app in OS X Yosemite 10.10.1 version, with Xcode version 6.1.1. Now, how do you check yours? To check for the version of OS, Click on the Apple button at the top left > Select About this Mac. You will get the following window.

OS version

To  find the version of your Xcode, open the Xcode > Select About Xcode, you will get the following window that displays the information of Xcode installed in your machine.

Xcode version

Getting Started

Now to start a new project, Open your Xcode. Click on Create a new Xcode project. You will notice that you will not be having the right pane , if you are opening Xcode for the first time.

Welcome to Xcode page

Xcode opens up a window to choose the template for the project.

Choose the template window

Let us select Single View Application and click next. We all know Rome was not built in a day, so let us create a simple application first and then see how to build multi-view and complex applications later.

Choose options for new project

Now, we must fill up our product name, organization name, organization identifier, then select our language and click next.

Location for storing project

Click create and your screen will look something like this.

Application main page

Now, click the main.storyboard, you will be able to see the screen below.

Main.storyboard of your application

Now, click on the view controller that is the big white box in the storyboard. Then click the file inspector button on the right top.

Inspector Pane

This section has identity and type section, interface builder document section, localization and target membership section. Scroll to the interface builder document and uncheck the Use Size Classes. Your screen will look like this after you uncheck it.

Disable size classes window

Click on the disable size classes. And you can notice that the view controller’s size has reduced to the size of the iphone 6 screen.

Window after you disable size classes

Now, drag a UILabel, a UITextfield, a UIPicker, a UIButton and a UILabel again from the Object Library. The last label is for displaying the result.  Now let us just run the app and see.

Output

Well, that does not look very good. Does it? We can make it a bit pretty by setting constraints for the picker so that the right side gap goes away. For that , go to the autolayout menu

AutoLayout Icons

Choose the pin i.e is the second button from the left and set the constraints according to your view. After that click on the add 3 constraints button (we have added three constraints here).

Set the constraints

Run the app and see if you like it. Else you can go ahead and change according to your choice. Once you have set constraints, your app looks something like this.

Output after setting constraints

Now that the picker is aligned, let us connect these objects to our view. Open up the assistant editor, we will see that the screen is split into two, one with the story board and another with the ViewController.m. Now change the screen from ViewController.m to ViewController.h

Open window in the assistant editor

Now to connect the objects to our view, press control and drag the object to ViewController.h inside the @interface and @end. Set the name and click connect.

Set IBOutlet for UITextField

Now you can see the connection as a black button next to the @property. When you click on it, it shows the connection.

Connection from Storyboard to ViewController.h

Now do the same for all the objects, whose value will be changed during the execution of the app. How do we identify such objects? For example, in our app the first label – that just displays enter the value, will not change its value while the application runs and the user does not interact with them . So for such kind of objects we will not need an IBOutlet. Only the objects that has user interaction will have IBOutlets.

After the connection has been set

Now for the button, we need to specify the action by control + drag the button inside th interface. Then change the connection from the outlet to action, set the name and click on connect.

Setting action for the convert button

Once we set everything, our ViewController.h looks something like this.

@interface ViewController :UIViewController
  @property (strong, nonatomic) IBOutlet UITextField *ValueTextBox; 
  @property (strong, nonatomic) IBOutlet UIPickerView *picker2;
  @property (strong, nonatomic) IBOutlet UILabel *ResultLabel;
  - (IBAction)Convert:(UIButton *)sender;
@end

Now run the app and see if there are any build errors. If there are no errors then continue with the next step, but we can see that the picker is empty and it does not contain any value. To use the picker we need to first change the ViewController.h file. Add UIPickerViewDelegate and UIPickerViewDataSource with the UIViewController in the @Interface declarative.

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController<UIPickerViewDelegate, UIPickerViewDataSource>
   @property (strong, nonatomic) IBOutlet UITextField *ValueTextField;
   @property (strong, nonatomic) IBOutlet UIPickerView *picker2;
   @property (strong, nonatomic) IBOutlet UILabel *ResultLabel;
   - (IBAction)Convert:(UIButton *)sender;

@end

To add content to the picker, we need to declare an array where each item will be displayed as a row of the picker. Go to the ViewController.h file and declare an array of type NSArray. Your view Controller.h will look like this:

@interface ViewController :UIViewController<UIPickerViewDataSource,UIPickerViewDelegate>
  @property (strong, nonatomic) IBOutlet UITextField *ValueTextBox;
  @property (strong, nonatomic) IBOutlet UIPickerView *picker2;
  @property (strong, nonatomic) NSArray *data;
  @property (strong, nonatomic) IBOutlet UILabel *ResultLabel;
  - (IBAction)Convert;
@end

Finally, just connect the storyboard picker view to the view controller as delegate and datasource by clicking on the UIPickerView and opening the Connections Inspector. Then, you click and drag from both the datasource and delegate outlets to the View Controller.

Setting Datasource and Delegate outlet to ViewController

Now that the connection is set up. Let us write the code now. To add data to the picker. Go to the ViewDidLoad method and initialize the array by adding the following code.

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    _data=@[@"Celsius",@"Fahrenheit"];
}

Now when you try to run your app, you will get an error message saying “terminating with uncaught exception of type NSException”. When you check the ViewController.m, you will see the following two warnings:

Viewcontroller.m

UIPickerView needs a way to display data to the user — i.e. from a data source. The data source protocol methods  provide the data to the UIPickerView for displaying to the end-user. The protocol says that the picker consists of standard methods that must be implemented for a UIPickerView to work. So add the following code in the ViewController.m file

#pragma mark pickerview datasource

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
  return 1;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
  return _data.count;
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
  return _data[row];
}

Once you add that, run the code again. You will see the picker has data in it. But then if you select/click on it nothing happens because we have not written any code for it.

To make something happen when we select it, we must include the delegate protocol methods. The method we need to add is the didSelectRow method that will perform whatever action we need on the selected row. Here in our app, we just need to return the value of the selected row into a string.

-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
  selectedValue = _data[row];
}

Now we can write the code for the button convert, but before that you can rename the labels and button and make it look nice.

second

The code for the button is :

-(IBAction)Convert:(UIButton *)sender 
{
 float res=0.0;
 float val=[_ValueTextField.text floatValue];
 NSLog(@"value %f",val);
 if([selectedValue isEqualToString:@"Fahrenheit"])
 { 
   //celsius to fahrenheit res=(val*1.8)+32;
 } 
else 
{ 
  //fahrenheit to celsius res=(val-32)/1.8;
}
NSString *final= [NSString stringWithFormat:@"%.02f",res];
_ResultLabel.text = final;
}

Now run the app, you will get the following screen, when you click on the textfield to enter value.

third

We know that, we must allow the user to enter only numbers. For that we need to click the text field in the story board and go to the attributes inspector and change the keyboard type to number pad.

Change attribute of TextField

Run the app again

first

We can enter only numbers and run the app safely. But here you can see that after entering the number the keyboard does not disappear. To deal with it and also add pictures and set backgrounds, wait for An iOS App a Click Away : Working with MultiComponent Picker

Got a question for us? Mention them in the comments section and we will get back to you. 

Related Posts:

Get Started with iOS Development

About Author
Divyamol
Published on Jun 15,2015
Divyamol is passionate about learning new technologies and exploring things around her. She is currently working in Edureka as a Quality Analyst.

Share on

Browse Categories

Comments
0 Comments