Search code examples
iosswiftxcodetableviewxib

How to resize custom cells in a TableView?


I am learning iOS development and Swift. I am trying to create a simple to-do app, with custom cells in a TableView. I have created the custom cell with a XIB file. In this, the cell looks like this:

What it's supposed to look like

However, when I run the app on the simulator, it looks like this:

What it actually looks like

Where am I going wrong and how can I Fix it?


Solution

  • You can fix the cell height to a default value by putting something like

    self.tableView.rowHeight = 44.0
    

    In your viewDidLoad, where tableView corresponds to the IBOutlet that is your UITableView in your xib file.

    If you would like to do this dynamically e.g. by calculating the size of the cell's contents and then resizing the cell so it fits nice and snug, you should implement

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 44 // The cell's height
    }
    

    Be sure to set your UITableView's delegate to self to use this last method.

    Please see this tutorial for more info.