3

I'm new to Swift and iOS programming and I'm having a play with making some simple apps. I am trying to build a master-detail app.

In the master view I've given the tableview two sections and I've set the content of the table view to "static cells". Initially I gave each section 3 rows and was able to successfully run the app with the following code in the mainviewcontroller file:

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

I am now wanting to have 11 rows in the first section, and 5 rows in the second section but the changes I have tried to the code prevent the app from running. I've tried:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 16
}

and I've tried:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 11
}

but it falls over. What am I doing wrong here?

Woody
  • 1,677
  • 7
  • 26
  • 32

1 Answers1

15

You should use the section to decide how many rows there should be in that section. For example, you could have a variable in your view controller:

let numberOfRowsAtSection: [Int] = [11, 5]

Now in numberOfRowsForSection:

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    var rows: Int = 0

    if section < numberOfRowsAtSection.count {
        rows = numberOfRowsAtSection[section]
    }

    return rows
}
ABakerSmith
  • 22,759
  • 9
  • 68
  • 78
  • 1
    how do I refer to the rows in each section specifically? For example, if I wanted to have the first section's rows say "Hi" and the second section's rows to say "hello", how do I differentiate between them in `cellForRowAt IndexPath`? Do they add to a total (if there are two sections, one with 11 and one with 5 rows... does the last row in the last section count as the 15th row?)? – Runeaway3 Oct 31 '16 at 18:14
  • 2
    Does the answer to this [question](http://stackoverflow.com/questions/29578965/how-do-i-populate-two-sections-in-a-tableview-with-two-different-arrays-using-sw/29579027#29579027) help? :) – ABakerSmith Nov 01 '16 at 00:46