Swift cell content not showing

Viewed 6655

I have a tableView that contains cells and each cell should contain an image, a label and a non-editable textView.

Here's what it displays instead: https://i.stack.imgur.com/WmOn3.png As you can see it shows an empty tableView but with the three top lines closer to each other.

ViewController.swift:

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

let food = ["Pasta-salad", "Hamburger", "Pancakes"]

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
    return (food.count)
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
{
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! TableViewCell

    cell.foodImage.image = UIImage(named: (food[indexPath.row] + ".jpg"))
    cell.foodLabel.text = food[indexPath.row]
    cell.foodDescription.text = ("insert description of \(food[indexPath.row])")

    return (cell)
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

TableViewCell.swift

class TableViewCell: UITableViewCell {

@IBOutlet weak var foodImage: UIImageView!
@IBOutlet weak var foodLabel: UILabel!
@IBOutlet weak var foodDescription: UITextView!

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
}
}

Main.storyboard: enter image description here

3 Answers

If your cells have a fixed height, set it in tableView.rowHeight.

But if you have a dynamic height, check your constraints. It's possible, that you have no constraints related to your cell's bottom.

Also Check Delegate and DataSource

tableView.delegate = self
tableView.dataSource = self

It seems like the height of cell 0.

Implement the UITableViewDelegate method for returning the height of each cell you can also return different height for each, by some calculation.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 100.0;//Choose your custom row height
}

You need to set your view controller as the tableview's delegate and dataSource.

Add this to your view controller:

override func viewDidLoad() {
    super.viewDidLoad()

    tableView.delegate = self
    tableView.dataSource = self
}
Related