iOS Tutorials: UITableView Item Clicked
iOS

Understanding UITableViewDelegate

UITableViewDelegate Methods

The delegate of a UITableView object must adopt the UITableViewDelegate Protocol. There are some optional methods which allow the user to manage selections, configure headings and footer section, provision to add cells, delete cells and reorder cells, and to perform other actions.

Before we start, make sure you have the UITableView implementation in front of you for understanding.

You can download a sample project from the link.

If you run the project (Command + R), this will be the output.

 

iOS Tutorials: UITableView Output
UITableView Output

If you see in our project,

We have used, didSelectRowAt indexPath method, which is helpful whenever a cell is selected, as in the above screenshot you can see the Alert, this alert will appear whenever an item gets selected.

iOS Tutorials: UITableViewDelegate method
UITableViewDelegate method

 

  • The showAlert method is something, which show’s an alert with custom alert title and message.
iOS Tutorials: Method to show Alert in swift
Method to show Alert in swift

Under UITableViewDelegate Protocol, user can use the following methods

 

iOS Tutorials: UITableViewDelegate Methods-1
Methods-1 : UITableView Delegate

 

iOS Tutorials: UITableViewDelegate methods-2
Methods-2 : UITableView Delegate
iOS Tutorials: UITableViewDelegate methods-3
Methods-3 : UITableView Delegate

 

iOS Tutorials: UITableViewDelegate methods-4
Methods-4 : UITableView Delegate

 

iOS Tutorials: UITableViewDelegate methods-5
iOS Tutorials: UITableView Delegate methods-5

 

If you see in the code, there is code

tableView.deselectRow(at: indexPath, animated: true)

whenever you click on a cell you can see a Gray coloured selection for a cell, and then it fades out.

This is possible with the help of this line, if you set the animated value as false, fade out behaviour will not be visible then

showAlert(withTitleAndMessage: “Alert!”, message: String(format: “%@ row is selected.”,String(indexPath.row)))

This line actually calls a method named as showAlert, which takes 2 parameters; one is the Title and another one is the Message.

This message actually shows an alert with a Title as “Alert!“, and a message “<row number> row is selected“.

 

iOS Tutorials: UITableView Item Clicked
UITableView Item Clicked

When it comes to, UITableViewDelegate protocol then, there are various methods, all the methods are documented here

Please browse our next article for getting more details on UITableViewDataSource, please visit this link.