chibro2 chibro2 - 2 months ago 13
iOS Question

Custom UITableViewCell only displays one UILabel, even though there are two on storyboard

I am making a simple contacts application with controllers:

ContactTableViewController
and custome cell:
ContactTableViewCell
. I created a custom table view cell where the style is custom,
identifier
is
ContactTableViewCell
, and class is also
ContactTableViewCell
.
The cell has two
UILabel
fields, which are exposed to
ContactTableViewCell.swift
class as follows:

import UIKit

class ContactTableViewCell: UITableViewCell {

@IBOutlet weak var name: UILabel!
@IBOutlet weak var info: UILabel!

override func awakeFromNib() {
super.awakeFromNib()
print("cell loaded with name: ", name)
// Initialization code
}

override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)

// Configure the view for the selected state
}

}


Now I want to display them in my
ContactViewController
, and the relevant part of my controller looks like this:

// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}


// here we communicate with parts of the app that owns the data
override func tableView(_ tableView : UITableView
, cellForRowAt indexPath: IndexPath
) -> UITableViewCell {

let id = "ContactTableViewCell"

// deque a cell as an instance of ContactTableViewCell
guard let cell = tableView.dequeueReusableCell(withIdentifier: id, for : indexPath)
as? ContactTableViewCell else {

fatalError("dequed cell is not instance of ContactTableViewCell")
}

cell.name.text = "hello"
cell.info.text = "hello information"


However, when I run the simulation I only see two rows of "hello", even though it should be something like:

hello
hello information


repeated twice. What is the problem here?

Answer Source

Most probably you don't have enough room to fit both labels. You can either set the row height in storyboard by:

  1. Selecting your tableview
  2. Go to size inspector
  3. Change the Row Height

Change row height

OR

You can implement tableView(_:heightForRowAt:) method in your tableView's delegate. i.e.

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    // return desired height for your cell
    return 90.0
}