iOS UITableView Tutorial for Beginners : Part 1

This tutorial will explain how to implement tableview in iOS. In this UITableView tutorial we will make an app that will show tweets TableView. In iOS, tableview is one of the most used feature and if you are a developer or want to be one, then you will be implementing it in almost all the apps you will make.

We will make a twitter like app with basic functionality and sudo data ( We will cover read data in advanced tutorial but the same logic will work). On clicking a cell, it will take you to a new screen and show the entire tweet. We will also learn how to pass data between different screens / viewcontrollers.

What exactly is a TableView

It is like a list which can be scrolled. Each item of tableview is called a cell. A tableview  cell can be just a text or text with some subtitle/detail text or an entire custom cell.

iOS TableView Tutorial

Here, I am using a subtitle cell. The tweets are titles whereas “via Codigator” is subtitle.

Examples of Tableview -

  1. The settings app on your iPhone is based on tableview.
  2. Twitter app – each tweet is a customized cell

Prerequisites

  • You should know hot to make outlets, IBActions (How To Make iPhone Apps)
  • Familiarity with dictionaries and arrays (Introduction To Dictionaries)

If you are not familiar with the basic then go to tutorials section and read the beginners tutorials first.

Theory

We will be setting delegate and datasource for our tableview. Don’t worry much about these terms right now.

  • Datasource – In layman’s language, a datasource asks the class to send the data to be shown on the cells and also number of cells
  • Delegate – As the name suggests, the class will act as delegate for the tableview. For eg. if some event took place on the cell (click,swipe) it will tell the class and the class will take appropriate actions as a delegate.

Setting Up The Views

Go to MainStoryboard.storyboard in the navigator panel. In the objects library, search for TableView and drag it (not TableViewController) onto your main view. Re-size the tableview so that it covers the entire screen. Now keeping the tableview selected, select attributes inspector (4th tab in Utilities View). Set the following properties for tableview

  • Content – Dynamic Properties
  • Prototype Cells -1

Now, select the prototype cell you just made on the tableview and in the attributes inspector set the following properties for it

  • Style – Subtitle
  • Identifier – SettingsCell

Finally, create an IBOutlet for the tableview in TVTController.m it between @interface TVTViewController () and @end and name it tableView.

Run the app. You should be able to see a blank scrollable TableView.

Adding Data To Our UITableView

Add an array to store tweets. Add the following code in between @interface TVTViewController () and @end.

@property (strong, nonatomic) NSArray *tweetsArray;

Next, add the following lines of code inside viewDidLoad, just below [super viewDidLoad]; method

  //1
  self.tableView.dataSource = self;
  //2
  self.tweetsArray = [[NSArray alloc] initWithObjects:
                      @"Always put your fears behind you and your dreams in front of you.",
                      @"A relationship with no trust is like a cell phone with no service, all you can do is play games.",
                      @"People should stop talking about their problem and start thinking about the solution.",
                      @"Dear Chuck Norris, Screw you. I can grill burgers under water. Sincerely, Spongebob Squarepants.",
                      @"My arms will always be open for you, they will never close, not unless you're in them.",
                      nil];

1)Firstly,  we set the tableViews data source as our class (self). We will handle the delegate later.

2) We allocate some memory to our tweetsArray and initialize it with demo tweets (strings). In Advanced tutorials, when we learn about twitter integration, we will use the same logic only this array will be fetched from Twitter API.

Next, Go to TVTViewController.h and replace the following line

@interface TVTViewController : UIViewController

with

@interface TVTViewController : UIViewController <UITableViewDataSource>

Right now, just add this line and don’t think too much about it. You will learn more about them in delegates and protocols tutorial. This code means that this class will be following some protocols defined in UITableViewDataSource. For example, we are going to use some methods which have no declaration in our current class. To make sure that our class know about the methods which we are going to use are declared in UITableViewDataSource, we use this technique.

Add the following methods in TVTViewController.m just before the last @end

//3</pre>
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [self.tweetsArray count];
}

//4
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
//5
static NSString *cellIdentifier = @"SettingsCell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

//5.1 you do not need this if you have set SettingsCell as identifier in the storyboard (else you can remove the comments on this code)
//if (cell == nil)
//    {
//        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellIdentifier];
//   }

//6
NSString *tweet = [self.tweetsArray objectAtIndex:indexPath.row];
//7
[cell.textLabel setText:tweet];
[cell.detailTextLabel setText:@"via Codigator"];
return cell;
}

3)This method is declared in UITableViewDataSource we added earlier and will be called whenever our class is ready to show the tableview. It expects us to return a value for the number of cells we want to create. In our case, we return the count of our array.

4)This method is again declared in UITableViewDataSource and will be called after the method  -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{} . It expects a cell we want to show. This method is called as many times as the number passed in method //3.

5)We create a static string called cellidentifier and set it’s value to SettingsCell ( we used the same name for our cell identifier in storyboard earlier). This will connect the prototype cell we made in our storyboard. Then we create a cell and with a function dequeueReusableCellWithIdentifier get a reusable cell with the identifier .To understand what reusable cell means, take an example tableview with 100 cells and only 10 cells currently showing on the screen. The device will not allocate memory to all 100 cells instead it will provide memory to some and keep resusing them. So our method here tells the OS to give us the reusable cell of the provided cell id. If not found, create a new one.

6)Then we fetch the object from tweetsArray at the index  using indexpath.row.

7)finally we set the text of cell’s texLabel (the title text) and   detailTextLabel (subtitle text) and return the created cell.

We are done her with the first part of the tutorial. Run the app (CMD+R) and scroll your tableview (It might not scroll  because you need to add more rows to it :)   so do that as an exercise)

Source Code

Download the complete source code here and if you have any questions use the comment section.

What Next

In the second part of this tutorial, we will be passing data between two screen and showing detailed screen of each cell when tapped.

iOS UITabelView Tutorial For Beginners : Part 2 – Passing Data
iOS UITableView Tutorial for Beginners : Part 3 – Custom Cells & Delegates

About Bharat

is an iOS developer and aims at helping people learn and master iOS development. He graduated from IIT Kanpur and loves gadgets and new technology. He is also the admin of this site.

6 comments

  1. Why is datasource assigned to self?

    Thanks for the tutorial.

    • self means this class (The class where you have used self). So assigning datasource to self means that this class will take care of the datasource methods of tableview.

  2. Very good tutorial. Thank you. Hoping you’ll have something about IBOutlets from STATIC custom cells. Looking for that, but all tutorials everywhere seem to only discuss dynamic cells. Thanks.

  3. thanks for the tutorial it helped me alot :)

  4. Hi,
    iam yesubabu,many times i used your tutoriel it is good .

    thanks for sharing your knowledge.

  5. Abdullah Darwish

    Thank you so much, that was very helpful

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Scroll To Top