Is it possible to have differing heights in a UITableView Cell when I use several different ways of displaying the cell?

后端 未结 11 1263
一整个雨季
一整个雨季 2020-12-21 19:25

I\'ve spent several days trying to figure this out, but there doesn\'t seem to be a solution. I have a very basic UITableView cell with two labels in it. One of them will be

11条回答
  •  生来不讨喜
    2020-12-21 20:16

    First of all, unless you need a UIStackView for some other purpose that you're not mentioning in your question, don't use them. Multi-line labels and dynamic height cells work well without them (don't needlessly complicate the code if they are not necessary).

    There are no bugs in iOS that stop this from working, that I'm aware of. Dynamically sized cells work great with Auto Layout, all you need to do is set the correct constraints in the cells and set the rowHeight and estimatedRowHeight properties of the table view.

    The most likely reason this is not working for you is that you have not put all the needed constraints in your cell. The needed constraints are:

    1. A top constraint from your cell content (i.e. your multi-line label) to the top of the cell content view
    2. A leading constraint from your single-line label to the left of the cell
    3. A trailing constraint from your multi-line label to the right of your cell
    4. A bottom constraint from the bottom of your multi-line label to the bottom of your cell

    I think you're missing point 4.

    Edit

    According to your comments, you're using a UIStackView so as to align the top baselines between the single and the multi-line labels. By this, I understand you want your labels to align like this:

    To get this behaviour, you don't need a UIStackView. Just give the labels constraints to allow the multi-line label to define the cell height. The following image shows the top baselines aligned between the two labels (i.e. the first lines of each label are aligned).

    Notice how the left label only needs a leading and top constraint, while the right label needs a top, trailing and bottom, because it defines cell height.

    In summary, dynamic table view cells require three things:

    1. tableView.rowHeight = UITableViewAutomaticDimension
    2. tableView.estimatedRowHeight = 100
    3. The cell content must have all four constraints (leading, trailing, top and bottom) to define cell height.

提交回复
热议问题