user7024499 user7024499 - 1 year ago 90
Swift Question

UITableView - What is indexPath?

I'm doing a tutorial online right now building out a table of cells and I have a question. In the second function tableView below... what exactly is indexPath?

More importantly, how does the program know to update the value being passed through indexPath by one each time the function is called?

var rowNumber = 0

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

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let rowCell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "Cell")
rowCell.textLabel?.text = String(indexPath.row + 1)
return rowCell

Answer Source

TableView is divided into sections. Each section contains some number of rows. IndexPath contains information about which row in which section the function is asking about. Base on this numbers you are configuring the cell to display the data for given row. Application is executing this function when it needs to display a row. For example you scroll the tableview down and next cell will appear on the screen. To configure this cell with, for example, correct texts, it's asking you what should be displayed on row which is at this position (section and row).

Also, to improve performance you should create the cell using tableView.dequeueReusableCellWithIdentifier function instead of Cell's init.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download