// How to create a simple UITableView with static data – Guilmo

How To simple UITableView

Published on March 4th, 2013 | by Guilherme Mogames

0

How to create a simple UITableView with static data


One of the most feared things to newbies (at least it was for me) is to create UITableViews. At first it looks scary, but it’s in fact really simple and quick to create your first UITableView.

The content below will help you get started in creating your first TableView with some static data. But remember that the information below is to help you get started and you can do the same examples as I’m going to teach you and after that you can play around changing other stuff in the code and trying to get dynamic data to fill your table.

Getting Started

The first thing you will need is data to populate your table. In order to have some data, we’re going to create a NSArray and set some static content for the purposes of this How To.

  1. Create a NSArray property (either in your .h file or inside the @interface in your ViewController.m file
    @interface ViewController ()
    @property (nonatomic,strong) NSArray *data;
    @end
  2. Inside your viewDidLoad method, let’s populate the array with some content.
    self.data = @[@"Apple",@"Banana",@"Peach",@"Grape",@"Strawberry",@"Watermelon"];

    Notice that we used Objective-C Literals to create this NSArray, optimizing the code. To learn more about Literals, visit http://clang.llvm.org/docs/ObjectiveCLiterals.html

  3. That’s it for the data creation. Once you’re getting used to creating your UITableView, you can go ahead and try getting dynamic data from APIs, SQLite database, etc…

Now that you have some data, we can create the UITableView and populate it with this data.

Creating a UITableView

  1. First thing you need to do is open your .XIB file to add that UITableView through the Interface Builder. In the Interface Builder, drag a Table View object into your interface.
    Objects-TableView
  2. Once your table is in the interface, you need to set who is going to be it’s delegate and data source, to do that press the “control” key on your keyboard and then click inside the table view and drag to File’s Owner. You will see a blue line connecting both the Table View and the File’s Owner. Once you connect with File’s Owner, you can release the mouse click.
    Connecting IB
  3. Once you connect and release the mouse click, a black popover will show up with two options, Delegate and DataSource. Click on delegate. After that, repeat the above step and this time select dataSource.
    You need to select the delegate and dataSource to tell the UITableView who’s going to control it and who’s going to provide the data to be used in the table view.
  4. Once you finish connecting, you will need to create an Outlet of the Table View in your controller and to do that first click in the Assistent Icon that is located in the top right corner of your XCode window. (it’s the icon in the middle inside the Editor section that has a bow tie).
    Assistant Icon
  5. This will open the Assistant Editor panel with your ViewController.h file. You will now need to connect your Table View below the @interface code. To connect, use the same steps as you did above, press “control” and click in your Table View and drag the line below @interface and release.
    Creating Outlet
  6. Once you release you will see another popover showing up for you to type a name to your IBOutlet. Type myTableView and click on Connect.
    IBOutlet
  7. Next thing is to tell your interface that it’s going to be a Table View delegate and dataSource, to do that open your ViewController.h file and add the following code after your @interface declaration
    <UITableViewDelegate, UITableViewDataSource>

    so your final ViewController.h file should look like this

    @interface ViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>
    @property (weak, nonatomic) IBOutlet UITableView *myTableView;
    @end
  8. Now that you’ve done that, let’s make some magic!

Making it Work!

When you add delegates and dataSources you will need to implement the required methods for them. For the UITableView, only the dataSource have required methods that you will need to implement.

– “but .gm. how do I know what are those required methods?”

Fear not! the easy way is to press the “command” key in your keyboard and click on the UITableViewDataSource that you added in the .h file. That will take you to the UITableView.h file for that specific method. And in there you will see the @required and @optional methods you can implement.
Required Methods

As you can see, we have two @required methods we need to implement in order to get the UITableView working. The numberOfRowsInSection and cellForRowAtIndexPath. Let see how to implement those

  1. Copy those two method, paste them in your ViewController.m file and replace the ending ; with {}
  2. The first method we are going to work with is the numberOfRowsInSection. This method tells the UITableView how many rows of content it will have. And to get this number we need to add a simple line of code
    return [self.data count];

    so your method will look like this

    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return [self.data count];
    }

    The [self.data count] will count and return the number of items in your Array.

  3. Going to the next method we need to load the Table Cell and change it’s label to match our data in the array, so the final code will be this
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{    
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];    
        cell.textLabel.text = [self.data objectAtIndex:indexPath.row];    
        return cell;    
    }

    The first line inside the method loads the cell using the dequeueReusableCellWithIdentifier, which means that it reuses the cell for all the cells in your table, reducing the amount of memory. So if your Table View only shows 10 cells at a time, and you have over 1000 cells, it will only load the 10 cells and reuse that to lower the memory usage. And this will make your table scroll more fluid.
    But in order to use that, we say that the dequeue uses a cellIdentifier, but where does that come from?

  4. In your ViewController.m file, below the @implementation ViewController, add the following code
    static NSString *cellIdentifier;
  5. In your viewDidLoad add the following code
    cellIdentifier = @"rowCell";    
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:cellIdentifier];

    The first line you are just giving the cellIdentifier a name. On the second line you’re registering the UITableViewCell class for using the cellIdentifier string we just created.
    We keep this piece of code out of the cellForRowAtIndexPath, otherwise every time the method is called, it would register the class and that would not do anything good.

  6. Going back to the cellForRowAtIndexPath method, the second line is
    cell.textLabel.text = [self.data objectAtIndex:indexPath.row];

    Which means that you are saying that the Cell Label value is self.data value at index indexPath.row (1, 2, 3, etc…). The indexPath.row is automatically grabbed.

  7. And finally, the last line is return cell; which just returns the cell to the Table View.

That’s it, you’re ready to build and run your app

UITableView Demo

This concludes the basic create your UITableView How To. But there are a lot of things you need to learn, and that will come in separated posts.

For now, I recommend also implementing the method

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{}

This will be called once the user taps in any of the cells. This will give you the index the user tapped so you can work your magic.

I’ve included the example using this method in the Demo Project, so download below and see for yourself.

Do you have any questions, comments, compliments? hit the comments below.

Thanks

.gm.

Tags: , , , , , , ,


About the Author

Founder of the Guilmo.com website and freelance iOS developer for over 2 years. Creator of one of the most used financial app in Brazil and also creator of the iPhone game FlyingMoo. Over 10 years of experience with IT and over 4 years as a Scrum Master for a large multinational IT company.



Leave a Reply

Your email address will not be published. Required fields are marked *

Back to Top ↑