I am populating a table view with items in a list and when I add multiple items to the table view, all of the cells except the first one is blank. And when I delete the cell lowest to the bottom of the screen, it puts the data from that cell into the next cell up. I'm not sure what I did wrong but here's my code if anyone is able to help.
import UIKit
// Initialize the list that populates the each cell in the table view
var list = [AnyObject]()
let cell = UITableViewCell(style: UITableViewCellStyle.default,
reuseIdentifier: "cell")
class FirstViewController: UIViewController, UITableViewDelegate,
UITableViewDataSource {
@IBOutlet weak var myTableView: UITableView!
// Declares how many rows the table view will have
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return (list.count)
}
// Populates each table view cell with items from each index in the list
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
// let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
// cell.accessoryType = .checkmark
// cell.textLabel?.textAlignment = .natural
// The text of the cell = the data of index that matches the index of the cell
cell.textLabel?.text = list[indexPath.row] as? String
// Sets the background color of the cell
// cell.backgroundColor = UIColor.clear
return cell
}
// Allows user to remove item from table view by swiping left
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
// if the user swiped left to delete an item from the table view
if editingStyle == UITableViewCellEditingStyle.delete
{
// remove the deleted item from the list and reload the data
list.remove(at: indexPath.row)
myTableView.reloadData()
}
}
I had the same issue, and in case any of the previous answers didn't work: I made most of the set up programatically.
Define global var
var cellsContent = [String]() // Change to any type you need
First create the cells with identifiers in viewDidLoad function:
cellsContent = ["Text1", "Text2"]
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.reloadData()
Populate each table view cell with the items in cellsContent var
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
let cell = UITableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.text = cellsContent[indexPath.row] as? String
cell.backgroundColor = UIColor.clear
return cell
}
Set sections and rows per section
override func numberOfSections(in tableView: UITableView) -> Int {
return 1 // Change as needed
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellsContent.count
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With