user3323258 user3323258 - 1 year ago 55
Swift Question

Programmatically created UITableViewCell only displaying its first subview with AutoLayout

I was writing an iOS app in Swift. I created a table view scene, but it is only displaying its first subview. I tried to make the code as simple as possible. I created a table view cell with two labels, but it still only displays the first label. The code is as follows. Why isn't the second label displayed? Are my AutoLayout constraints wrong? Thanks!

import UIKit

class TestCell: UITableViewCell {
let viewsDict: [String : UILabel] = [
"first": UILabel(),
"second": UILabel(),

override func awakeFromNib() {
viewsDict["first"]!.text = "first"
viewsDict["second"]!.text = "second"
viewsDict["first"]!.translatesAutoresizingMaskIntoConstraints = false
viewsDict["second"]!.translatesAutoresizingMaskIntoConstraints = false
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[first]-[second]-|", options: [], metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[first]", options: [], metrics: nil, views: viewsDict))
contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[second]", options: [], metrics: nil, views: viewsDict))

class TableViewController: UITableViewController {

override func viewDidLoad() {

override func didReceiveMemoryWarning() {

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)


Answer Source

From your comment it sounds like you're asking how to set the height of the cell programmatically and automatically. There are a few different ways to do this:

Closest to what you probably want, in iOS 8 and after, you can have the tableView calculate this itself:

self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 60.0;

You can also just set the rowHeight property of your tableView and have every row be the same height:

self.tableview.rowHeight = 60.0

Or you can implement the delegate method to calculate row height on the fly. This way also allows you to inspect each individual cell and determine how tall you should make the view:

func tableView(_ tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    let cell = tableView.cellForRowAtIndexPath(indexPath) as! TestCell
    // Calculate the height that you want ..
    let height = 60.0
    return height

This StackOverflow post goes into much greater depth on automatically sizing a UITableViewCell.