Friday, March 3, 2017

iOS : TableView Controller in Swift 3.0

Table View is a vey common and important component to develop application. Usually application contains table view to display bulk of data in single screen.  You can customise table view and make it attractive and eye catching whatever you want to do. It is as simple as other development platforms. However, here I am giving you How to integrate simple table view in iOS application in Swift 3.0.

As you can see in the picture above, We are going to print one list of my friends. Moreover, we will add feature to delete some name from the item list. I assume you know how to create xCode project and familiar with Swift language, Storyboard and xCode 8.

Now let's start from scratch. Create a project named TableViewDemo in xCode and remove initials default file ViewController as we are not going to use it. Additionally, Go to Storyboard and delete ViewController as well. 

Select your project and press Command+N OR go to File > New > File. Select Cocoa Touch Class and hit Next button.
Add Class name as per your choice but it should be meaningful so we can identify it. To give a better and meaningful name is also important for code development as we need to identify file from bunch of file in big project. Here, I am using "FriendsListController", Choose subclass of : UITableViewController. Don't change anything except this two name. then hit next and press create button.
Here you have created swift file for Table view successfully.  This swift file behaves like backend code part. But You also need to bridge with UI part which you are going to build in Storyboard file. Open Storyboard and Go to Object Library from Right - Bottom part as described in below image and drag-drop TableView Controller into our Storyboard file.

You can also add Navigation bar to your controller for navigating between one screen to another. For that, Go To Editor > Embed In > Navigation Controller. Rest of the work xCode do by itself but make sure you have selected correct ViewController in which you want to add.

Now, We need to tell xCode that this TableView controller is associated with "FriendsListController" file which we have built earlier. For that Go to Storyboard and select TableView Controller > Identity inspector. Add Class name in class field as described below.

Now the file is bridged with UI Controller. One more thing you need to do before leave Storyboard is to give Cell name. For that select Cell which is added by default in table view. Select it and go to Attributes inspector. Add value of Identifier to "Cell". We will use this identification in swift file later.

So, your storyboard looks like below screen.

Now Backend part begins. open FriendsListController File and follow below steps. One of the main component which uses for TableView is Array. It is best way to store list of data into array and integrate it into Table View. It is very simple and efficient way. We will do the same and have created my friend list array and declare it in our file globally. Here is my sample data:

var friendsName = ["Parth Pandya","Aangan Bhatt", "Krishna Pandya","Anuj Patel","Maulik Soni","Vidit Maniyar","Hardik Bhatt"]

We have used var instead of let just because we are going to remove some list item as well in future. I assume you are aware of basic fundamental of let and var datatypes.

You have noticed that some of override methods has been added by default in our class and made it commented. Just uncomment these methods as per our requirement or you can create it again. We will understand each and every methods step by step.

1. numberOfSections : Copy below code into your file

override func numberOfSections(in tableView: UITableView) -> Int {
        return 1

We can set multiple section and bifurcate as per our data but we are using same type of data in single list item so we set it 1. 

2. cellForRowAt indexPath:

 override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = friendsName[indexPath.row]
        return cell

This method defines cell by it's identifier which we have added in storyboard. and then based on that cell we can access cell components like, label, button etc. Label is added by default in tableView cell. IndexPath defines index level of tableView, based on index path we can retrieve data from Array and set it into label. It is as simple as given above.

3. didSelectRowAt indexPath:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You clicked \(indexPath.row) row: Friend Name:\(friendsName[indexPath.row])")

Action required when user clicks on specific item. This method fulfil it and we can add action here. Currently I am printing selected item name in console.

Here, is a code for tableView is completed, if you want to swipe delete action then copy below code in the file.

 override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        return true
    override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
        if editingStyle == .delete {
            friendsName.remove(at: indexPath.row)

Above code is override methods to call swipe delete button and perform action when user clicks on Delete button. In this code, we just remove clicked data from array and reload table again.

That's it... Now run the project... It will give you same result as mentioned in first demo image.

Transfer data from one screen to another

For the same example, usually you need to transfer user selected data to another screen. You can do this with more few line of code. Here, When user selects name from friend list, it will redirect to next screen and print selected friend name on screen. I assume you know how to connect two screen with segue in storyboard. Before start understand the steps below:

1. Create another file where you want to transfer data
2. Add segue to connect two controller and name that identifier segue.
3. perform segue in controller from where you want to redirect with data.
4. Set redirected data into the screen. Thats it.

First, Create new cocoa touch swift file named "DetailedViewController" and same as above create new View Controller in Storyboard as well. Same as above, name those view controller and connect it with the swift file. Add one label and connect outlet to our swift file. It will define label into DetailedViewController.

Second, We need to connect FriendsListController and DetailedViewController via segue in storyboard. For that, open storyboard and select Friend List Controller. For that you need to click on Yellow button over the controller as described below.

Click this yellow button + Control Key to create segue between two screen. Drag and Drop it to DetailViewController screen. It will create segue between two. Now, you can see DetailedViewController also get Navigation by default. Name this segue "detailedSegue". We will use this identifier later to access this navigation segue. Your storyboard will look like :

Here, Storyboard task ended, now we need to add some code in both files. For that open "DetailedViewController" swift file and add below code into it.

class DetailedViewController: UIViewController {

    var selectedFriendName : String!
    @IBOutlet weak var friendNameLabel: UILabel!
    override func viewDidLoad() {

        friendNameLabel.text = "Selected Friend is \(selectedFriendName!)"

Now Open FriendsListController file and add below code:

1. Create one String variable to store selected data:

var selected : String!

2. Modify didSelectRowAt: methods as below:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You clicked \(indexPath.row) row: Friend Name:\(friendsName[indexPath.row])")
        selected = friendsName[indexPath.row]
        self.performSegue(withIdentifier: "detailedSegue", sender: self)

3. Add prepare segue navigation method:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if(segue.identifier == "detailedSegue"){
            let destinationController = segue.destination as! DetailedViewController
            destinationController.selectedFriendName = selected

First, we have store selected data in separate variable and call segue in didSelectRowAt: method. prepare segue method is override,  we check segue identifier which we have added in storyboard. If it matches the we have pass selected name to DetailedViewController variable.  Thats It. Now run the project. 

I hope, this tutorial will clear your confusion regarding table view and make it useful. You can download full source code from here.

No comments:

Post a Comment