How to implement UITableView programmatically using Swift

When implementing a UITableView in your iOS application you will usually select a master-detail application:

Master Detail Application Swift

Once the project is selected the UITableView implementation is ready for you to start adapting in your application, but sometimes your need just a tableView.

The implementation of the tableView is very simple to do in Swift. Start by implementing the following functions:


optional public func numberOfSectionsInTableView(tableView: UITableView) -> Int 
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)

This function is optional per documentation: “Default is 1 if not implemented”

optional public func numberOfSectionsInTableView(tableView: UITableView) -> Int 

Lets start the implementation of our tableView.

-Open Xcode and go to the file menu and select new and select new project or press Ctrl+Shift+N.
-Select the name of your project.
-Select the location where you want to save your project.

Single View Application Swift

Go to ViewController (ViewController.swift). In your ViewController you need to add the following delegates:

UITableViewDelegate,UITableViewDataSource

It will look like this:

class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource

Now you need to add the variables. Choose a variable where you are going to store the objects you are going to display in your tableView:

var tableView: UITableView  =   UITableView()
let animals : [String] = ["Dogs","Cats","Mice"]

Now you need to initialize and set your tableView variable:

tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
tableView.delegate      =   self
tableView.dataSource    =   self
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
self.view.addSubview(self.tableView)

Because you are using only one section you are not going to implement the following function:

optional public func numberOfSectionsInTableView(tableView: UITableView) -> Int 

Now you need to get the count of elements you are going to display in your tableView:

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return animals.count
        
    }

Now you need to assign the values in your array variable to a cell:

    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        
        let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
        cell.textLabel!.text = animals [indexPath.row]
        return cell;
    }

Now you need to register when user taps a cell:

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        print(animals[indexPath.row])
        
    }

Your implementation should look like this:

import UIKit

class ViewController: UIViewController, UITableViewDelegate,UITableViewDataSource {
    var tableView: UITableView  =   UITableView()
    let animals : [String] = ["Dogs","Cats","Mice"]
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        tableView = UITableView(frame: UIScreen.mainScreen().bounds, style: UITableViewStyle.Plain)
        tableView.delegate      =   self
        tableView.dataSource    =   self
        tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
        self.view.addSubview(self.tableView)
        
        
    }
    
    
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return animals.count
        
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        
        let cell:UITableViewCell=UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "cell")
        cell.textLabel!.text = animals [indexPath.row]
        return cell;
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        print(animals[indexPath.row])
        
    }
}

If you click on the Run in your Xcode project should look like this:

UITableView Xcode Swift

Please let me know if you have any questions by leaving a comment below or on twitter @luisemedr

How to create UITableView programmatically in Objective-C

Usually when you need to implement tableview in your app you select a master-detail application:

new Xcode project Master detail

Were you get the project all the UITableView implementation ready for you to start adapting in your application,but sometimes you need just a tableView either to display the configuration of your app or to display some other kind of information.

The implementation of the tableview is very simple to do. You need to implement the following methods:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;

This method is optional if you have only one section in your tableview:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;

Lets start implementing our tableview.

– Open Xcode and go to the file menu and select new and select new
project or press Ctrl+Shift+N.
– Select single view application and click next.
– Select the name of your project.
– Select the location where you want to save your project.

new Xcode project single view application

Go to viewController implementation file (viewController.m).

In the interface line you need to add the following delegates:

UITableViewDelegate,UITableViewDataSource

It will look like this:

@interface ViewController () <UITableViewDelegate,UITableViewDataSource>

Bellow the @interface line we need to add two properties a tableview property and NSArray property for our content in the tableView:

@property (strong,nonatomic) UITableView *table;
@property (strong,nonatomic) NSArray     *content;

In your viewDidLoad method we are going to add few lines of code. First we need to create our content using the NSArray. We are going to use the days of the week for this example.

self.content = @[ @"Monday", @"Tuesday", @"Wednesday",@"Thursday",@"Friday",@"Saturday",@"Sundayā€¯];

Now that we have our content we need to initialize our tableview and set the delegate and data source for our tableView. First we are going to initialize our tableView Property. We are going to initialize the frame of the tableview with the bounds of our view and we are going to select the style UITableViewStylePlain

self.table = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];

We have initialized our tableView property now we need to assign the delegate and data source:

self.table.delegate = self;
self.table.dataSource = self;

and the last line of code in your viewDidLoad will be to add the tableView to the main view:

[self.view addSubview:self.table];

Now we are going to implement the number of sections in the table view:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

As I mentioned before this method is optional . By default the number of sections is 1.

In numberOfRowsInSection we are going to use the count of elements in our NSArray to tell the tableView how many rows we are going to be using:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _content.count;
}

time to populate our tableView. We need to implement the following method:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath

Inside of this method we need to create a static property to identify the cells in our tableView and initialize UITableViewCell:

static NSString *cellIdentifier = @"cellIdentifier";
UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:cellIdentifier];

Now we need to add some safety checking in our cells in case they are null:

if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }

The last part of the implementation in this method is to actually assign the values of our NSArray to the cells:

cell.textLabel.text =  [_content objectAtIndex:indexPath.row];

The last method we are going to implement is didSelectRowAtIndexPath to register when the user taps in a cell. At this point we are only going to log when the user has tap in the cell:

NSLog(@"title of cell %@", [_content objectAtIndex:indexPath.row]);

Your implementation should look like this:

@interface ViewController () <UITableViewDelegate,UITableViewDataSource>

@property (strong,nonatomic) UITableView *table;
@property (strong,nonatomic) NSArray *content;


@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self cofigureTableview];
    self.content = @[ @"Monday", @"Tuesday", @"Wednesday",@"Thursday",@"Friday",@"Saturday",@"Sunday"];
    
}

-(void)cofigureTableview
{
    self.table = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    self.table.delegate = self;
    self.table.dataSource = self;
    [self.view addSubview:self.table];

}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _content.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"cellIdentifier";
    
    UITableViewCell *cell = [self.table dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if(cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
        
    }
    cell.textLabel.text =  [_content objectAtIndex:indexPath.row];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
{
    NSLog(@"title of cell %@", [_content objectAtIndex:indexPath.row]);
}

If you click on the run in your Xcode project should look like this:

Xcode project with tableview Objective-C

Please let me know if you have any questions by leaving a comment below or on twitter @luisemedr