Search code examples
iosswiftuitableviewautolayoutxib

Table View in Xib file doesn't load custom table view cell properly


I have a Xib with a table view in it (I'm using a Xib and not a regular storyboard because I'm inserting the Xib into a UIPageViewController). In the Xib's class, I register a custom table view cell. Though the cell inserts into the table view, it doesn't resize properly based on it's constraints nor does it change the display of the table view.

Here's my xib: enter image description here

Here's my custom cell: enter image description here

And here's the setup code I have in the view controller that has the table view Xib:class

YearbookPageViewController: UIViewController {
    var signatures: [Signature] = []
    var pageNumber: Int = 0

    convenience init(signatures: [Signature], pageNumber: Int) {
        self.init(nibName: "YearbookPageViewController", bundle: nil)
        self.signatures = signatures
        self.pageNumber = pageNumber
    }

    // MARK: Properties
    @IBOutlet var pageTableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()

        self.pageTableView.delegate = self
        self.pageTableView.dataSource = self

        let nib = UINib(nibName: "SignatureTableViewCell", bundle: nil)
        self.pageTableView.register(nib, forCellReuseIdentifier:  SignatureTableViewCell.identifier)
    }

}

When I run the app, this is what it looks like:

enter image description here

So basically the custom cell is added to the table view from the xib file, but they aren't sized properly even though the cell has constraints on everything? And, the rest of the tableview is still white with table view lines? I'm not sure if the table view isn't responding correctly because it's in a Xib or if I'm missing something that I'm supposed to add.

Would appreciate any pointers or help on how to get things displaying properly!


Solution

  • By default, tableView displays default height of UITableViewCell. If we want custom height, there can be two ways.

    1. Using heightForRow method

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 200
    }
    

    2. Using AutoLayout

    In this case, your tableView cell must apply all required constraints that completes a top to bottom constraint ladder, so that autoLayout can calculate the height of cell at RunTime.

    For the second problem, you can remove extra separator. by executing following code in viewDidLoad

    tableView.tableFooterView = UIView()