Reputation: 185
I was watching this Youtube tutorial on how to dynamically add cells to a UITableView in Swift.
I followed the video down to a tee but author neglected to show his UITableView Custom cell file, so I believe that that is where my issue is.
Again my issue is my data in my array foods is not showing, and I am unable to add data to my array.
Here is my viewController class -
import UIKit
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var addFoodtextField: UITextField!
var foods: [String] = ["Bananas", "eggs", "grapes"]
override func viewDidLoad() {
super.viewDidLoad()
tableView.tableFooterView = UIView(frame: CGRect.zero)
}
@IBAction func addButtonTapped(_ sender: Any) {
insertNewFoodTitle()
}
func insertNewFoodTitle() {
foods.append(addFoodtextField.text!)
let indexPath = IndexPath(row: foods.count - 1, section: 0)
tableView.beginUpdates()
tableView.insertRows(at: [indexPath], with: .automatic)
tableView.endUpdates()
addFoodtextField.text = ""
view.endEditing(true)
}
}
extension ViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return foods.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let foodTitle = foods[indexPath.row]
let cell = self.tableView.dequeueReusableCell(withIdentifier: "foodCell") as! foodCell!
cell?.foodTitle?.text = foodTitle
return cell!
}
}
And here is my foodCell class
import UIKit
class foodCell: UITableViewCell {
var foodTitle : UILabel?
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
This is my app in the interface builder
and this is what I see when my app runs
Upvotes: 0
Views: 871
Reputation: 5616
You are missing two lines in viewDidLoad()
:
override func viewDidLoad() {
super.viewDidLoad()
tableView.dataSource = self // This class is the tableview's data source
tableView.delegate = self // This class is the tableview's delegate
}
Upvotes: 2