4

Aim:

  • To display a multiline label on a custom cell in a UITableView using autolayout and UITableViewAutomaticDimension.
  • The cell should vary based on the text in each UILabel.

What I have done:

  • Used auto layout
  • tableView.rowHeight = UITableViewAutomaticDimension
  • tableView.estimatedRowHeight = 100
  • label.numberOfLines = 0 (label is the new label I created)
  • label.setTranslatesAutoresizingMaskIntoConstraints(false)
  • Added UILabel to the contentView
  • Added constraints from the UILabel to content view

Problem:

  • Some text gets clipped (...) when I use a custom cell
  • Sometimes the scrolling is not very smooth

Tried same with UITableViewCell:

  • tableView.rowHeight = UITableViewAutomaticDimension
  • tableView.estimatedRowHeight = 100
  • textLabel.numberOfLines = 0 (textLabel already exists in UITableViewCell)
  • Scrolling seems smooth
  • No clipping, text is displayed correctly
  • Printed the cell.textLabel?.preferredMaxLayoutWidth and it shows 0

Question:

  • Why is it working fine with UITableViewCell and not my custom cell ?
  • In both cases the preferredMaxLayoutWidth is not being set.
  • Pls let me know what I am missing.

Code for my custom cell:

    class MultilineLabelCell : UITableViewCell {

    let label = UILabel()

    //MARK: Initializers

    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)

        setup()
    }

    required init(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)

        setup()
    }

    //MARK: Setup Views

    func setup() {
        setupLabel()
        setupLayout()
    }

    func setupLabel() {

        label.setTranslatesAutoresizingMaskIntoConstraints(false)

        label.numberOfLines = 0

        contentView.addSubview(label)
    }

    func setupLayout() {

        let views = ["label" : label]

        let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-[label]-|",
            options: .allZeros,
            metrics: nil,
            views: views)

        let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-[label]-|",
            options: .allZeros,
            metrics: nil,
            views: views)

        contentView.addConstraints(horizontalConstraints)
        contentView.addConstraints(verticalConstraints)
    }
}

View Controller Code

override func loadView() {
    super.loadView()

    tableView.registerClass(MultilineLabelCell.self, forCellReuseIdentifier: ViewController.cellIdentifier)

    tableView.rowHeight = UITableViewAutomaticDimension
    tableView.estimatedRowHeight = 100

}
    func populateData() {

        dataArray.append("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat")

        dataArray.append("Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum")


        dataArray.append("Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam,")

        dataArray.append("nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?")

        dataArray.append("But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?")
    }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCellWithIdentifier(ViewController.cellIdentifier) as! MultilineLabelCell

        cell.label.numberOfLines = 0
        cell.label.text = dataArray[indexPath.row]

        return cell
    }

enter image description here

Hem Poudyal
  • 321
  • 6
  • 16
user1046037
  • 16,755
  • 12
  • 92
  • 138
  • You are using story board or code? Its working fine for me with code with some modification. – Amit89 May 21 '15 at 04:53
  • No i register the cell for the table view programmatically and then deque the cell. Pls try with a very long text that changes for every indexpath. – user1046037 May 21 '15 at 05:32
  • Try set the preferredMaxLayoutWidth on your label to the labels bounds – Daniel Galasko May 21 '15 at 06:03
  • Definitely setting the preferredMaxLayoutWidth works. The question that I have is that I tried printing the textLabel.preferredMaxlayout width which is zero for the UITableViewCell even after layoutIfNeeded and yet it works. So was wondering if UITableViewCell.textLabel is doing anything differently. – user1046037 May 21 '15 at 06:07

1 Answers1

2

While giving constraints programatically views/controls in content view of UITableViewCell and want to have dynamic cell size based on your text length, you need to give padding from all four sides explicitly(provide some value). Do changes as per below. Looks like a bug

In setupLayout method

func setupLayout() {

        let views = ["label" : label]

        let horizontalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("H:|-5-[label]-5-|",
            options: .allZeros,
            metrics: nil,
            views: views)

        let verticalConstraints = NSLayoutConstraint.constraintsWithVisualFormat("V:|-5-[label]-5-|",
            options: .allZeros,
            metrics: nil,
            views: views)

        contentView.addConstraints(horizontalConstraints)
        contentView.addConstraints(verticalConstraints)
    }
Amit89
  • 3,000
  • 1
  • 19
  • 27
  • The only difference I see is that you are displaying the same text for the 3 cells. I am displaying different text for the cells. I will try it though – user1046037 May 21 '15 at 06:01
  • What you need to is to provide left, right,top,bottom margin in cell content view constraints. I edited the answer. – Amit89 May 21 '15 at 06:32
  • My understanding is as long as there is no ambiguity and the constraints is exhaustive it is fine. I think the constraints that I have added in the code is exhaustive. – user1046037 May 21 '15 at 12:50
  • 1
    May be, i modified and gave values for left, right,top,bottom as per my edited code and it worked superbly. – Amit89 May 21 '15 at 12:54
  • Thank you !!! Very strange ... `H:|-[label]-|` seems to cause the issue. (The text gets clipped). When it is replaced with `H:|-8-[label]-8-|` it works fine without another code change. I was understanding both are the same. `-` simply meant default spacing. But that fixes the issue. Pls can you edit your answer and remove all code and replace it with the text so that I can mark it as the correct answer. – user1046037 May 22 '15 at 01:29
  • This is excellent. Thank you. It seems like a bug perhaps, I just assumed that the content view would have some kind of constraint making it size itself to be large enough to contain all its subviews. This "extra" constraint is much better than other solutions of calling layoutIfNeeded or subclassing and setting minimum widths in layoutSubviews. – David Feb 11 '16 at 23:49
  • @David, Thank you. Glad it helped you. – Amit89 Feb 20 '16 at 14:59