Liumx31
Liumx31

Reputation: 1210

Configure UITableView with different number of rows in different sections

I have a UITableView which has multiple sections and I want each section to have a different number of rows. What I have in code right now is

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    //habitsByDay is a global array contain the number of rows for each section, 
    //with each index of the array corresponding to the each of the sections
    return habitsByDay.removeAtIndex(0)
}

Will this method be called when each section is loaded (i.e. it should be called habitsByDay.count-many times).

Upvotes: 1

Views: 1494

Answers (2)

Kian
Kian

Reputation: 122

You have to use if statements for that. For example:

if (section == 0) { //First section
return 20; }        //20 rows in first section

if (section == 1) { //Second section
return 10; }        //10 rows in second section

Or in your case for example.

if (section == 0) {
return habitsByDay.count }

Upvotes: 0

Martin R
Martin R

Reputation: 539685

The table view data source methods can be called at any time, in any order. In particular, they should not have side effects as in your example.

If habitsByDay is an array with the number of rows for each section then just do

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return habitsByDay[section]
}

Upvotes: 3

Related Questions