Understanding UITableViewDataSource

iOS Tutorials: UITableView Output

UITableViewDataSource Methods

The controller or an object which needs to make change using the UITableView Object needs to implement the UITableViewDataSource protocol.

There are some optional methods as well some required methods which allow the user to construct or modify a UITableView.

Before we start make sure you have the UITableView implementation in front of you for better 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

 

UITableViewDataSource protocol has 2 required methods; these methods are mandatory in the class, which has adapted to this protocol.

iOS Tutorials: UITableViewDataSource methods
UITableViewDataSource methods

 

Without implementing these methods we cannot proceed further, there are various other methods that can be explored here.

iOS Tutorials: UITableViewDataSource methods
UITableViewDataSource methods

 

iOS Tutorials: UITableViewDataSource methods
UITableViewDataSource methods

We have implemented the UITableViewDataSource required methods in our project as explained below in the snapshot.

 

iOS Tutorials: Understanding UITableViewDataSource methods
Understanding UITableViewDataSource methods

We will now be discussing a brief about the 2 methods:

  • numberOfRowsInSection:
    • This method is required for letting the UITableView know that, how many rows or we can say items needs to be displayed; as we have given then number as 20, so a list of 20 items will be displayed.

Ex: There an application of news domain, where we need to show a list of news, there will an API which will be giving us the list, so the API will be returning the count of items/news. That count need’s to be returned in this method, based on this only, the other method will play the role.

  • cellForRowAt indexPath:
    • This method is responsible for each and every item’s UI, that how a particular item will be displayed on the UI.
    • Reuse identifier, which we set for a UITableViewCell, in the attribute inspector, is used for identifying an item.
    • We can show a different kind of UI using the same method with the help of different cells and their identifiers.

Ex: There is news listing to be shown and the requirement like; there should be a news image (thumbnail image), there should be a title of the news and a small description as well; so this kind of design needs to be made in the storyboard and with the help of identifiers and UITableViewCell custom classes we can achieve this.

 

Author: Chandra.rao

iOS Developer. #Life of an developer.... Learn New technology, Code, Learn New Technology, Code, Death.