Showing posts with label Cocoa. Show all posts
Showing posts with label Cocoa. Show all posts

Sunday, April 1, 2012


Now that we have created a simple window base application we will move on to create a simple Tab Bar Application. To start with open XCode again and create a Tab Bar Application like below:
Tab Bar App
Then I am going to call mine MyNewTabApp, but feel free to name yours whatever is the most appropriate for you.
Name Tab App
Now for this tutorial I am going to use Interface builder a little bit. Click on the MainWindow.xib file. it should look like this afterwards:
Main Window XIB
If it might look like this:
Main Window XIB Alternate
If this is the case I recommend pulling the small vertical bar on the left of the graph paper to the right until it looks like the first picture. Ok, now that we XCode looking the way we want lets dive into creating the Tab Application. If we build and run the app is it is created for us, we have two tabs and views that are associated with them. The tabs say First View and Second View and you can toggle between them by pressing the tabs at the bottom.
Basic Tab Bar App
Now if our goal is to create a simple application that has four pages we will need to add two more pages to our app. To start this control click on the MyNewTabApp folder in the file view. Then click “New File…” choose the UIViewController subclass option and click next.
UIViewController
Make sure that the “With XIB for user interface has been chosen” and click next.
XIB Checked
I usually put in ThirdViewController as the name especially when creating very simple applications, but feel free to use whatever name you want. Then choose save. Make sure to repeat these steps again for the fourth tab. Now that we have all the view created lets add some stuff to views three and four so we know they are displaying. For view three we will add a Label. Click on the Third View’s xib file and then the view object. Open the Utilities view by clicking on the third View option in the top right of XCode. This will open all the utilities on the right of the IDE. Go down to the objects on the bottom right and drag the label object over to the view. You can make the label say whatever you want. It should look like this:
Setting Up Label
For view four we are going to change the background color. To do this click on the Fourth View’s xib file. Then click on the View object. Next make sure that you have the Utilities View open and click on the Attributes Inspector on the right. You should see a section for view and in that section there is an option for background color. Change that to something that stands out. I chose green:
Setting Up Background Color
Now go back to the Mainwindow.xib file we are ready to link our Tab Bar Controller with the two new View Controller. Go down to the objects in the bottom right hand corner:
View Controller Highlighted
Drag the View Controller object over from the bottom right to the Tab Bar Controller and place it after the second View Controller. Then bring a Tab Bar Item and place it underneath the View Controller Object you just brought over so it looks like this:
Tab Bar Item
Now we are ready to link this item with your view. Click on the third View Controller and then click the Identity Inspector on the right. After this load you can choose from the drop down in the Custom Class section the class you used for the third view. Repeat these steps for the fourth view as well. Then Save, Build and Run. The third tab should look like this:
Third View App
The fourth tab should be nice and green or whatever color you used like this:
Fourth View App
If you want you can edit the names that show up on the tab items by double clicking on them. You can also click on the attributes inspector and the editing the Title text field under bar Item.

————————————————————–
As always, please leave your comments on iPhone applications, development, or any questions you might have.  Lets Get Started!

reference

Hello world for iPhone Developer


Step 1: Download XCode and the SDK

The first thing we need to do is to download the development tools namely XCode and the SDK. To download either of these you will need to register for the Apple ID and Apple developer Connection (ADC). Install both these tools, the procedure to do so is fairly trivial so I am not going into details.
 


Step 2: Create a new Project

Now we have the tools we need to start coding but before we do we need to create a new project.Select File > New Project orApple Key + Shift + N to bring up the new project menu. Select the Applications item of theIPhone OS section from the menu on the left, and select View Based Application from the icons on the right. When prompted enter a project name, I have used HelloWorld in the sample code.


When you create a project you will see a window similar to the one shown in the image on the right. There are four files in the Classes package;
HelloWorldAppDelegate.h
HelloWorldAppDelegate.m
HelloWorldViewController.h
HelloWorldViewController.m

We do not need to change the HelloWorldAppDelegate but just for information I would like to highlight some important parts of the auto-generated code.
The delegate header file contains a reference to a UIWindow object (Line 14) which controls all the user interaction for this application and will manage all other interface components. It also contains a reference to HelloWorldViewController (Line 15) which we will see later manages our one sample view.

In the source file for the application delegate (HelloWorldAppDelegate.m) we find an auto generatedapplicationDidFinishLaunching method. This, as the name suggests, invoked when the application has been loaded and in this method we will add our HelloWorldViewController object to the UIWindow and make it visible;
22    [window addSubview:viewController.view];
23    [window makeKeyAndVisible];  

The IPhone SDK UI follows the Model View Controller (MVC) design pattern and hence each view  has a corrsponding View Controller Object. XCode has automatically created a view for us, (its defined in the HelloWorldViewController.xib file you can see it by double clicking it in the side menu) and linked it to HelloWorldViewController. We now need to add controls to the view handle the generated events. Note we can add controls via a GUI interface called the Interface Builder but I am using the programmatic way for this tutorial. 


Step 3: Adding Controls and Handler to header file


Open the HelloWorldViewController.h file and within the curly braces delinting the HelloWorldViewController interface declaration add the following lines;

IBOutlet UIButton *button;
IBOutlet UILabel *label;
IBOutlet UIView *myView;


We are defining a view to display and a button and label to go in the view. After the curly braces add a method declaration to accept the click event of the button and also properties to access the  UI elements; myButton, myLabel and myView. Your entire code should look something like this:

1    #import <UIKit/UIKit.h>
2
3    @interface MyHelloWorldViewController : UIViewController 
4    {
5
6        IBOutlet UIButton *button;
7        IBOutlet UILabel *label;
8        IBOutlet UIView *myView;
9    }
10
11    -(IBAction)handleEvent:(id)sender;
12    @property (nonatomic, retain) UIButton *button;
13    @property (nonatomic, retain) UILabel *label;
15    @property (nonatomic, retain) UIView *myView;
16
17    @end


Step 4: Adding Controls


First add a synthesize the three UI elements to create the getter and setters. Add the following two lines of code after the @implementation HelloWorldViewController command in line 11 of HelloWorldViewController.m file. 

@synthesize button;
@synthesize label;
@synthesize myView;

Now find the comment saying "Implement loadView if you want to create a view hierarchy programmatically." and un-comment the loadView method that follows this line. Add the following lines to the method to create a button and label;
1    - (void)loadView 
2    {
3    // create and configure the view
4    CGRect cgRct = CGRectMake(0.0, 0.0, 480, 320); //define size and position of view 
5    myView = [[UIView alloc] initWithFrame:cgRct]; //initialize the view    
6    myView.autoresizesSubviews = YES;              //allow it to tweak size of elements in view 
7    self.view = myView;        

8    
// create a UIButton (UIButtonTypeRoundedRect) and play arround with settings
9    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];    
10   button.frame = CGRectMake(100, 100, 100, 50); // size and position of button
11   [button setTitle:@"Add" forState:UIControlStateNormal];
12  button.backgroundColor = [UIColor clearColor];
13  button.adjustsImageWhenHighlighted = YES;     

14  
//Add action handler and set current class as target
15  [button addTarget:self action:@selector(action:) forControlEvents:UIControlEventTouchUpInside];

16  //Display Button
17  [self.view addSubview:button];
        
18  //create a label
19  cgRct = CGRectMake(100, 170, 100, 50); //define size and position of label
20  label = [[UILabel alloc] initWithFrame:cgRct];
21  label.text = @"Hello World";

22  //Display Label
23  [self.view addSubview:label];
24  }


Click the Build and Go button to check your interface is drawn correctly It should look something like to screen shot below.
 


Step 5: Handling Actions



We have already told the button to send an event (action) to the current class (self) in case of anUIControlEventTouchUpInside event but there is no handler defined to accept the event. We define a handler method in the class by adding the method shown below. It is doing two things, changing the text property of the label and adding a message to the log file.  
 
1    -(void)action:(id)sender
2    {
3        NSLog(@"UIButton was clicked");
4        label.text = @"Bye World";
5    }


Now click the Build and Go button again and click the button. The text of the label should change.


Reference
-http://www.tuaw.com/2009/04/27/iphone-dev-101-the-hello-world-app/

Friday, March 30, 2012

iPhone Table view with Images


Now that we have created a simple table view example we can look at extending our code to change the cell style. In so doing we will make use of the image and detailed text properties of the cell object to add images and subtitles to each row of the view. The first step is to add an image to the resources of our project. If you already have an image file that is suitable for this purpose feel free to use it in this example. Alternatively, we can pick up an image from the Mac OS X system on which Xcode is running. To add an image file to the application resources, right click on the Resources entry in the Groups and Files panel of the main Xcode project window. From the resulting menu, select the Add -> Existing Files… option. In the resulting file selection panel navigate to and select your pre-existing image file. Alternatively, enter apple.png into the search field and press Enter. The apple.png file should appear in the file list from where it can be selected:

Adding an image file to the resources of an Xcode project

Once the appropriate image file has been selected, click on the Add button to add the image to the resources. On the following panel accept the default settings and click Add once again.
Now that the image is included in the project resources it is time to add some code to the cellForRowAtIndexPath method in the TableExampleViewCrontoller.m file. All we need to do in this file is add some code to create a UIImage object from the image file and assign it to the imageView property of the cell object. With these changes made, the method should read as follows:
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
        // Configure the cell.
        UIImage *cellImage = [UIImage imageNamed:@"apple.png"];
        cell.imageView.image = cellImage;
        cell.textLabel.text = [self.colorNames objectAtIndex: [indexPath row]];
        return cell;
}
Next, we want to add a subtitle to the text of each cell. This is achieved by assigning a string to the cell object’s detailTextLabel text property. Note also that the code currently selects the UITableViewCellStyleDefault cell style which does not display the detailText. It will also be necessary, therefore to change the cell style to UITableViewCellStyleSubtitle . With all of these changes implemented, the method now reads as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

        // Configure the cell.
        UIImage *cellImage = [UIImage imageNamed:@"apple.png"];
        cell.imageView.image = cellImage;

        NSString *colorString = [self.colorNames objectAtIndex: [indexPath row]];

        cell.textLabel.text = colorString;

        NSString *subtitle = [NSString stringWithString: @"All about the color "];
        subtitle = [subtitle stringByAppendingFormat:colorString];

        cell.detailTextLabel.text = subtitle;

        return cell;
} 
Once the changes have been made to the code, build and run the application. When the simulator starts up the table view should appear with images and subtitles as shown in the following figure:

iPhone table view with subtitles and images
References

iPhone hide Status Bar

The Status Bar (or UIStatusBar) is the 20-pixel-high strip at the top of the window that shows the carrier name and signal strength, network status, current time, and battery strength:
Default
Black Opaque
Black Translucent
The status bar can be gradient gray (with black text), black opaque (with white text), or black translucent. By default the status bar is gray. If your app features standard iPhone UI elements, then stick with the default status bar. However if your app has custom views with dark backgrounds, then a black status bar will look better.
Black and white status bars push the underlying views down, giving you 320 x 460 pixels of screen space to work with in your app. A translucent status bar overlays the underlying view, giving you the full 320 x 480 pixels of screen space. (More on sizes)
You can set the status bar style either programmatically or in your Info.plist file. If you change it in Info.plist, then the style is changed when the app launches (while the app is loading). If you change it programmatically, then the style changes after the app finishes loading.
To change the status bar style in Info.plist, look for your Appname-Info.plist file in the Resources group of your Xcode project. To add a new element to this file, click on the last line of options so that the + symbol appears on the right. Click it, then enter UIStatusBarStyle in the left column. After you set that, the right column will then change to a list of options:
To change the style programmatically after the app has launched, add this line to your app delegate's applicationDidFinishLaunching method:
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackTranslucent];
Valid status bar styles are UIStatusBarStyleDefault, UIStatusBarStyleBlackTranslucent, and UIStatusBarStyleBlackOpaque.

Hiding the Status Bar

You can also hide the status bar completely, but give some consideration as to whether you should do this. From the iPhone Human Interface Guidelines: "People expect to be able to see the current battery charge of their devices; hiding this information, and requiring users to quit your application to get it, is not an ideal user experience."
To hide the status bar when the app launches, add a new line to Info.plist and enter UIStatusBarHidden in the left column. The right column will change to a checkbox:
To hide the status bar after the app has completely launched, change it programmatically by adding this line to your app delegate's applicationDidFinishLaunching method:
[[UIApplication sharedApplication] setStatusBarHidden:YES animated:NO];
If you set animated to YES then the status bar will disappear by fading out.

Additional References

Sizes of iPhone UI Elements

ElementSize (in points)
Window (including status bar)320 x 480 pts
Status Bar
(How to hide the status bar)
20 pts
View inside window
(visible status bar)
320 x 460
Navigation Bar44 pts
Nav Bar Image /
Toolbar Image
up to 20 x 20 pts (transparent PNG)
Tab Bar49 pts
Tab Bar Iconup to 30 x 30 pts (transparent PNGs)
Text Field31 pts
Height of a view inside
a navigation bar
416 pts
Height of a view inside
a tab bar
411 pts
Height of a view inside
a navbar and a tab bar
367 pts
Portrait Keyboard height216 pts
Landscape Keyboard height162 pts

Points vs. Pixels

The iPhone 4 introduced a high resolution display with twice the pixels of previous iPhones. However you don't have to modify your code to support high-res displays; the coordinate system goes by points rather than pixels, and the dimensions in points of the screen and all UI elements remain the same.
iOS 4 supports high resolution displays (like the iPhone 4 display) via the scale property on UIScreen, UIView, UIImage, and CALayer classes. If the object is displaying high-res content, its scale property is set to 2.0. Otherwise it defaults to 1.0.
All you need to do to support high-res displays is to provide @2x versions of the images in your project. See the checklist for updating to iOS4 or Apple documentation for Supporting High Resolution Screens for more info.

Adjusting Sizes

Click here to see how to adjust View Frames and Bounds.

Additional References