Search code examples
iosuitableviewautolayouttableviewheight

Dynamic Height Cell with XIB: Including UILabel and UIImageView


I’m trying to design a UITableViewCell with XIB that has the following layout and behavior:

  1. A UIView on the left with a fixed size of 44x44.
  2. A UILabel next to it, which expands dynamically based on the text length.
  3. A UIImageView below the label, which resizes its height proportionally to its maximum width (maintaining aspect ratio).

Unfortunately, I can’t get this to work properly with Auto Layout. I keep running into issues with either dynamic sizing not working as expected or constraint errors.

Here’s an illustration of the layout I am trying to achieve: enter image description here

Requirements:

1. UIView: Fixed size: 44x44. Positioned on the left.

2. UILabel: Should expand dynamically in width and height based on the text length.

3. UIImageView: Should stretch to the maximum width of the cell. The height should be proportional to the width (e.g., maintaining a 16:9 aspect ratio).

-> To achieve this layout, I need guidance on: What constraints should I define for UIView, UILabel, and UIImageView in XIB to ensure proper behavior? How can I make the UILabel expand dynamically based on its content while ensuring the cell height adjusts correctly? How can I make the UIImageView responsive, maintaining its aspect ratio while fitting the maximum width of the cell?

Any help or suggestions would be greatly appreciated! Thank you!


Solution

  • If you want to do this in a XIB, it is fairly straightforward using a horizontal UIStackView to hold the 44x44 view and the label, and vertical UIStackView to hold that stack view and the UIImageView...

    XIB layout

    Set the horizontal stack view properties to:

    horiz

    and the vertical stack view properties to:

    vert

    for each, adjust the Spacing as desired.

    Note that the bottom constraint on the vertical stack view has its Priority set to 999 ... that prevents auto-layout complaints, both at design-time and run-time.

    Looks like this when running:

    start

    scrolled