I created a tableview with a custom cell showing data. The display works fine. But the cells are repeating so there are more cells being displayed then items in the array.
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// when searchcontroller is active, return the number of search results. If inactive simply return the count of the full AED list.
return self.AEDItems.count
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.AEDItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
let cell:CustomTableViewCell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! CustomTableViewCell
// Check if controller is active. If user is doing a search retrieve the aeds from the search result rather than the AED array.
let aed = self.AEDItems[indexPath.row]
cell.addressLabel?.text = aed.owner
cell.objectLabel?.text = aed.street
return cell
}
Why is this happening? I guess it has something to do with the cell reuseage. But does the count of items does not solve it?
The problem is this method:
This method is asking for the number of sections. You should return simply
1
from this method.Instead, you have as many sections as you do objects in your
AEDItems
array. And then in your other methods, you're not putting any section specific logic. So every section is identical to each other. But we actually only want one section with many rows.So, we actually want simply:
Or, as @johnpatrickmorgan clarifies in the comments, we can omit this optional protocol method entirely, as
UITableView
assumes only a single section if itsdatasource
has omitted this method.For more reading, check out the UITableView Data Source protocol documentation regarding
numberOfSectionsInTableView:
.