Handle Row Selection in UITableView – Swift

We hope you already finished previous 2 tutorials for UITableView : UITableView in Swift and UITableView With Customize UITableViewCell in Swift.

Now Before proceeding, I would like to share little knowledge on What UITableViewDelegate. There are 2 types of delegate methods : Required and Optional.

For Implementing UITableVIew We already Added 2 Required methods : numberOfRowsInSection and cellForRowAtIndexPath, UITableView Must confirm to this delegate methods. On Another hand there are some method with Can be Implemented If required.

Handling Row Selection

There are many delegate methods provided for UITableView. Understanding Delegate is more importantbefore actually implementing.

For making you understand I will put it in simple words as:

Suppose you have 2 objects: ObjectA and ObjectB.

Now If you want a system in which ObjectA tells ObjectB to perform Certain task in such a way that,  ObjectA should know when ObjectB is Done with that task and it may take certain action depending on out come. This is achieved by Delegation in iOS.

There are many optional delegate methods provided by UITableView, you can refer them on Apple’s iOS Documentation website.

didSelectRowAtIndexPath is one of such methods which is triggered when user selects particular cell in table view.

In this tutorial we are going to show UIAlert with the selected Cell’s Title text.(name of the selected wonder).

Lets add Code to our App.

1
2
3
4
5
6
7
8
9
...
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
var alertView = UIAlertView()
alertView.addButtonWithTitle("Ok")
alertView.title = "Row Selected"
alertView.message = self.tableData[indexPath.row]
alertView.show()
}
...

Add this function to your code.

Thats is..! Simple hummm….. GO And Run you code.

RowSelection_UITableView_Swift

If you are facing any problem, you can always get the source for the above Demo HERE.