The UITableViewDelegate is used to control how the table is displayed, and UITableViewDataSource is used to define the UITableView’s data. There are two required methods and many optional ones which can be used to customize size, sections, headings, and cells in the UITableView.


UITableViewDataSource

Required Methods

numberOfRowsInSection: This method defines how many cells will be displayed in each section of the tableview.

Objective-C

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

// Return the number of rows for the table view. Usually populated from an array, // or can be statically defined. return self.myArray.count;

}

Swift 3

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

// Return the number of rows for the table view. Usually populated from an array, // or can be statically defined. return self.myArray.count

}

cellForRowAtIndexPath: This method is where the UITableView’s cells are created and configured. Should return either a UITableViewCell or a custom subclass.

Note: Using dequeueReusableCellWithIdentifier:forIndexPath: requires that the class or nib has been registered for that identifier using the UITableView’s registerClass:forCellReuseIdentifier: or registerNib:forCellReuseIdentifier: methods. Usually, this will be done in the UIViewController’s viewDidLoad method.

Objective-C

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

MyCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@“MyCustomCell” forIndexPath:indexPath];

// All additional customization goes here cell.titleLabel.text = [NSString stringWithFormat:@“Title Row %lu”, indexPath.row];

return cell;