articles

Home / DeveloperSection / Articles / iOS : Creating a UITableView Project

iOS : Creating a UITableView Project

Tarun Kumar2752 22-Jul-2015

In this article we are going to create a sample using UITableView to display a list of colors and also providing the facility to delete any color from the list, but at first we need to know some other important topics (some topics we already described in the previous project) to understand how those works and what are the uses in our project:

UITableView: (Display data in a list of plain, sectioned or grouped rows) Table view is one of the common UI elements in iOS apps. Most apps, in some ways, make use of Table View to display list of data. The best example is the built-in Phone app. Your contacts are displayed in a table view. Another example is the Mail app. It uses Table View to display your mail boxes and emails. Not only designed for showing textual data, Table View allows you to present the data in the form of images. The YouTube and Airbnb apps are great examples for the usage.

UITableViewDelegate: The delegate of a UITableView object must adopt the UITableViewDelegate protocol. Optional methods of the protocol allow the delegate to manage selections, configure section headings and footers, help to delete and reorder cells, and perform other actions.

UITableViewDataSource: The UITableViewDataSource protocol is adopted by an object that mediates the application’?s data model for a UITableView object. The data source provides the table-view object with the information it needs to construct and modify a table view.

NSMutableArray: The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray.

Creating a UITableView Project:

create a new project using the “Single View application” temple.

create the user interface and add the table view. Select “SimpleTableViewController.xib” to switch to the Interface Builder.

In the Object Library, select the “Table View” object and drag it into the view.

Your screen should look like below after inserting the “Table View”.


iOS : Creating a UITableView Project

Adding Table Data

In the Project Navigator select “SimpleTableViewController.h”. Append “<UITableViewDelegate, UITableViewDataSource>” after “UIViewController”. Your code should look like below:

@interface ViewController : UIViewController <UITableViewDelegate,UITableViewDataSource>

@end

The “UITableViewDelegate” and “UITableViewDataSource” are known as protocol in Objective-C. Basically, in order to display data in Table View, we have to conform to the requirements defined in the protocols and implement all the mandatory methods.

Next, select “ViewController.m” and define an instance variable for holding the table data.

@implementation ViewController{

    NSArray *colors;

}

    In the “viewDidLoad” method, add the following code to initialize the “tableData” array. We initialize an array with a list of colors.

    - (void)viewDidLoad {

      [superviewDidLoad];

    // Do any additional setup after loading the view, typically from a nib.

       colors = [NSArrayarrayWithObjects:@"Red",@"Green",@"Blue",@"Yellow",@"Orange",@"White",

    @"Pink",@"Black", nil];

    }

      Finally, we have to add two datasource methods:

      - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

         return [colorscount];

      }

      Next, we implement the other required methods.

         // The “cellForRowAtIndexPath” is called every time when a table row is displayed.

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

      (NSIndexPath *)indexPath {    

      staticNSString *simpleTableIdentifier = @"TableCell";    

         UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:

      simpleTableIdentifier];    

          if (cell == nil) {

            cell = [[UITableViewCellalloc] initWithStyle:UITableViewCellStyleDefault

      reuseIdentifier:simpleTableIdentifier];

          }    

          cell.textLabel.text = [colorsobjectAtIndex:indexPath.row];    

          return cell;

      }

      Connecting the DataSource and Delegate

      Go back to the “SimpleTableViewController.xib”. Press and hold the Control key on your keyboard, select the Table View and drag to the “File’s Owner”.

      Release both buttons and a pop-up shows both “dataSource” & “delegate”. Select “dataSource” to make a connection between the Table View and its data source. Repeat the above steps and make a connection with the delegate.That’s it.

      Finally, it’s ready to test your app. Simply hit the “Run” button and let the Simulator load your app:

      iOS : Creating a UITableView Project

      Delete a Row from UITableView

      There are three main things we need to do:

      1. Write code to switch to edit mode for row deletion

      2. Delete the corresponding table data from the mode

      3. Reload the table view in order to reflect the change of table data 

      1. Write code to switch to edit mode for row deletion

      - (void)tableView:(UITableView *)tableView commitEditingStyle:

      (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

         [colorsremoveObjectAtIndex:indexPath.row];    

         [tableView reloadData];

      }

      2.Delete the corresponding table data from the mode:

      Replace the NSArray with NSMutableArray because the problem of NSArray is it's non-editable. That is, you can’t add/remove its content once the array is initialized. Alternatively, we’ll change the NSArray to NSMutableArray, which adds insertion and deletion operations:

      @implementation ViewController{

         NSMutableArray *colors;

      }

      - (void)viewDidLoad

      {

         [superviewDidLoad];

      // Do any additional setup after loading the view, typically from a nib.

        colors = [NSMutableArrayarrayWithObjects:@"Red",@"Green",@"Blue",@"Yellow",@"Orange",

      @"White",@"Pink",@"Black", nil];

      }

      In the tableView:commitEditingStyle method, add the following code to remove the actual data from the array. Your method should look like this:

      - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

          [colorsremoveObjectAtIndex:indexPath.row];

      }

      3.Reload the table view in order to reflect the change of table data

          Therefore, once the underlying data is removed, we need to invoke “reloadData” method to request the table View to refresh. Here is the updated code:

      - (void)tableView:(UITableView *)tableView commitEditingStyle:

      (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

          // Remove the row from data model

          [colorsremoveObjectAtIndex:indexPath.row];

          // Request table view to reload    

          [tableView reloadData];

      }

      Test Your app and Delete a Row

      Try to run your app again and swipe to delete a row. You should be able to delete it.

      iOS : Creating a UITableView Project
      After Deletion "White" color is now removed from the list, see below:

      iOS : Creating a UITableView Project


      Updated 07-Sep-2019

      Leave Comment

      Comments

      Liked By