Reputation: 395
I'm trying to build an TableView with two sections. The second section should be filled with data from an array. The Storyboard has a TableView with static cells. There are two sections each with one cell.
If there is only one item in the textSectionTwo
array it just works fine, but breaks when there are more items in it
* Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
Below the code:
enum TableViewSections {
case sectionOne
case sectionTwo
}
class TableViewController: UITableViewController {
struct Identifier {
static let sectionOneCell = "SectionOne"
static let sectionTwoCell = "SectionTwo"
}
let textSectionOne = "Section 1"
let textSectionTwo = ["Section 2 - Row 1", "Section 2 - Row 2"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier.sectionOneCell)
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier.sectionTwoCell)
tableView.reloadData()
}
// MARK: - Table view data source
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch sectionForIndex(section) {
case .sectionTwo?:
return textSectionTwo.count // <- breaks when return is > 1
case nil:
fatalError("Unexpected value")
default:
return super.tableView(tableView, numberOfRowsInSection: section)
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch sectionForIndex(indexPath.section) {
case .sectionOne?:
return self.tableView(tableView, sectionOneCellForRowAt: indexPath)
case .sectionTwo?:
return self.tableView(tableView, sectionTwoCellForRowAt: indexPath)
case nil:
fatalError("Unexpected value")
}
}
private func tableView(_ tableView: UITableView, sectionOneCellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.sectionOneCell, for: indexPath)
cell.textLabel?.text = textSectionOne
return cell
}
private func tableView(_ tableView: UITableView, sectionTwoCellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: Identifier.sectionTwoCell, for: indexPath)
cell.textLabel?.text = textSectionTwo[indexPath.row]
return cell
}
func sectionForIndex(_ index: Int) -> TableViewSections? {
switch index {
case 0:
return .sectionOne
case 1:
return .sectionTwo
default:
return nil
}
}
}
EDIT:
In this sample code from Appple is something similar to my problem. They're using Static Cells and add content through code.
Upvotes: 1
Views: 671
Reputation: 8157
Static table view is used for presenting table view with static cells UI and data in it. It will use only those cells that you have made in the Storyboard.
Solution: use dynamic table view. It will allow you to present as many row as you want.
Upvotes: 2