Wednesday, October 31, 2012

UITableViewCell Using Interface Builder

Creating your own tableview cell could be such a hassle when you do it programmatically. To be able to follow this tutorial, you need to know how to add a tableview first. Refer to the previous tutorial on how to add a tableview if you still don't know how to add it yet.

Let's start!

1. Add a new file of subclass UITableViewCell.

2. After adding a new UITableViewCell class, only .h and .m files are created. So, let's add another file, an empty Interface Builder Document (xib file). Name it with the same name with our .h and .m files (to avoid confusion).

You should have these files in your project navigator.

3. Drag a tableview cell to your xib file, and change its class to SampleTableCell (the one we added a while ago).

4. Start customizing your cell. Here in my example, I want to make a feed cell (One with profile pictures, name, status, date <-- something like that):

  1. I changed the height of my cell to 90 (instead of the default cell height which is 44).
  2. I wanted to put a background image to my cell, so I added a UIImageView with size same with my cell. (I added an image to the project for my cell background.)
  3. All the other UIs are placed on top of the UIImageView (cell background). I added another UIImageView for the profile pictures. 

  4. Added a UILabel for the name, status and date.

My customized cell currently looks like this. Nice thing of doing it here in Interface Builder is that you can easily manipulate the positions, and other attributes of your objects.

3. Make an IBOutlet property of the objects that might change dynamically. In our example, our profilePicture object may change dynamically, depends on who posted what, the Name, Status, DatePosted. But the background image doesn't really change no matter who posted what, so we don't have to make an IBOutlet property of the background UIImage. And remember to synthesize these objects.
//Inside .h file

@property (nonatomic, strong) IBOutlet UIImageView *profilePicture;
@property (nonatomicstrongIBOutlet UILabel *name;
@property (nonatomicstrongIBOutlet UILabel *status;
@property (nonatomicstrongIBOutlet UILabel *datePosted;

//Inside .m file
@synthesize profilePicture;
@synthesize name;
@synthesize status;
@synthesize datePosted;

4. Connect these outlets to your objects in your xib file.

5. Create a new File, subclass of NSObject. This file will serve as our "User" object. This class must hold the important information we need, like the profilePicture filename, Name, Status and DatePosted.
//User.h file

@interface User : NSObject
@property (nonatomiccopyNSString *avatarFname;
@property (nonatomiccopy) NSString *name;
@property (nonatomiccopy) NSString *status;
@property (nonatomiccopy) NSString *datePosted;
//User.m file
@implementation User
@synthesize avatarFname;
@synthesize name;
@synthesize status;
@synthesize datePosted;

6. Create your user objects and put them all in your items Array. (This part is found in step 7 from the tutorial link above).
//I created five users. Sample code...

    User *user1 = [[User alloc] init]; = NSLocalizedString(@"Jennifer Eve Curativo", @"name");
    user1.status = NSLocalizedString(@"Currently addicted to Hi Fi Camp - It's a Japanese band, by the way. ;)", @"status");
    user1.datePosted = NSLocalizedString(@"October 31, 2012 5:30PM", @"date Posted");
    user1.avatarFname = @"jen.png";

//Put them all in our array list

items = [[NSArray alloc] initWithObjects: user1, user2, user3, user4, user5, nil];

7. Before we proceed, change the cell's Identifier. We need it later.

Remember the Datasource and Delegate methods of our tableView from the previous tutorial? We are going to modify/add some methods.

8. Remember that our customized cell's height was changed to 90, right? It has become taller than the usual height of our tableViewCell. Add this method so that our tableView will know that the cell's height was changed.
//If we did not change the height of our cell, we do not need to add this method.

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90.0;

9. Lastly, modify this method cellForRow. This is the part where we tell the tableView that we will use our custom cell.

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *CellIdentifier = @"MyFeedCell";
    SampleTableCell *cell = (SampleTableCell *) [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray* topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"SampleTableCell" owner:self options:nil];
        for (id currentObject in topLevelObjects) {
            if ([currentObject isKindOfClass:[UITableViewCell class]]) {
                cell = (SampleTableCell *)currentObject;
    // Configure the cell.
    User *user = [items objectAtIndex:indexPath.row];
    cell.profilePicture.image = [UIImage imageNamed:user.avatarFname]; =;
    cell.status.text = user.status;
    cell.datePosted.text = user.datePosted;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;

10. Hit Run!

Tuesday, October 23, 2012

Adding a UITableView Tutorial

For beginners, this is one of the difficult views to learn, anyhow let's learn how to add a tableview in our view.
A tableView is used to show a list of objects.

Adding a TableView Using Interface Builder

1. Prepare the superview of your tableView. (Superview is the view where we would like to put our tableview.) In our example, the UIViewController's view is going to be our tableView's superview.

2. Drag a tableView UI to our View.
If you hit run, you will see your tableView on your screen. You can scroll it up and down.

3. Set the tableview datasource and delegate in your Interface file.

@interface ViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>

4. Add an IBOutlet tableview property and synthesize it.

@property (nonatomic, strong) IBOutlet UITableView *sampleTableView
@synthesize sampleTableView; //.m file below @implementation ViewController

5. Connect your IBOutlet to our tableView in your xib file.

6. Create an array that will hold your list for you. If your items are static (will not change), use NSArray, else, if somewhere in your program, you need to change your array, use NSMutableArray.

@property (nonatomicstrong) NSArray *items;

7. In your viewDidLoad function, allocate and initialize your array with your objects. Currently, let's use simple string objects, NSString.
items = [[NSArray alloc] initWithObjects:@"Item No. 1"@"Item No. 2"@"Item No. 3"@"Item No. 4"@"Item No. 5"@"Item No. 6", nil];

8. Set our sampleTableView's datasource and delegate to its File's Owner.

9. Lastly, implement the UITableView Datasource and Delegate methods. These are necessary to manipulate our tableView.

#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    // Return the number of rows in the section.
    // Usually the number of items in your array (the one that holds your list)
    return [items count];

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    //Where we configure the cell in each row

    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell;
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    // Configure the cell... setting the text of our cell's label
    cell.textLabel.text = [items objectAtIndex:indexPath.row];
    return cell;

 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
 // Return NO if you do not want the specified item to be editable.
 return YES;

 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view

 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath

 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
 // Return NO if you do not want the item to be re-orderable.
 return YES;

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    // Navigation logic may go here. Create and push another view controller.
    // If you want to push another view upon tapping one of the cells on your table.

     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];

10. Hit Run!

Adding a TableView Programmatically

1. From the steps we had above, delete the tableView UI in our xib file, and delete the IBOutlet from our tableView property.

@property (nonatomicstrongIBOutlet UITableView *sampleTableView

2. On your viewDidLoad function (of your ViewController.m file). Follow the commented steps.

- (void)viewDidLoad {
    [super viewDidLoad];
    //Create a tableView programmatically
    self.sampleTableView = [[UITableView alloc] initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.yself.view.frame.size.widthself.view.frame.size.height 2) style:UITableViewStylePlain];
    //Add the tableview as sa subview of our view ---> making "view" our superview.
    [self.view addSubview:sampleTableView];
    //From step 7 above.
    items = [[NSArray allocinitWithObjects:@"Item No. 1"@"Item No. 2"@"Item No. 3"@"Item No. 4"@"Item No. 5"@"Item No. 6"nil];
    //From the step 8 above, this is how we do that programmatically

3. Done! When you hit run, you'll see the same result.

Tuesday, October 2, 2012

Navigation Controller and a Tabbar Controller in One View

If wanted to show a Navigation Controller and a Tabbar Controller in one view, should the navigation controller be inside the tabbar controller or is it the other way around? 

Most beginners happen to do this in an INappropriate manner. The answer to my first question is that the Navigation Controller should be put inside the Tabbar Controller. And the worst part for those who do not know how to do that is that they will just put a Navigation bar at the top part of the view. Don't do this, let me help you how to do it properly.

If you could still remember how we created a Tabbed Application, do it first before following the next steps. Follow this tutorial up until Step 10. (

Let's Begin!

1. Expand the Placeholders/Objects Panel, and the Tab Bar Controller. Drag a Navigation Controller Object under the TabBar Controller.

2. Since I only want two tabs for my TabBar Controller, I will make my first tab a Navigation-Based view, so I will delete one View Controller bellow the Navigation Controller object.

For Step 1 and 2.

I edited the tint of the Navigation Bar and its Navigation Title.

Hit run and it should look like this.

3. Did you follow the tutorial above and reached step 10? If so, I'll assume that you created two view controllers already (the FirstViewController and the SecondViewController). In my FirstViewController, I added a button which will be used later on in this tutorial.

4. Import the two ViewControllers, then, go back to our MainWindow.xib, change the class of the ViewController inside the Navigation Controller. So as the ViewController inside the Tabbar Controller.

5. Create another ViewController, let's name it "ThirdViewController," put a label to indicate that it's the ThirdVC.

6. Import ThirdViewController in FirstViewController Class. Create an IBAction method that will push the ThirdVC and show it.
- (IBAction)goToThirdView:(id)sender {
    ThirdViewController *thirdVC = [[ThirdViewController alloc] init];
    [self.navigationController pushViewController:thirdVC animated:YES];

7. Connect the IBAction to our Button in FirstViewController.xib.

8. Hit Run, and you should be able to navigate from FirstVC to the ThirdVC and still have the TabbarController.