8

I want to use a horizontal stack view to place an icon (UIImage) next to a label (UILabel). I want it so the icon is always the same height as the label's text. If the user increases the system font size, I want the icon to adjust accordingly to remain the same height.

Note the stack view with the icon and label are in a UITableViewCell.

How can I do this?

So far I have the following AutoLayout settings:

  • UITableViewCell height set to default.
  • Stack view constrained to the size of the UITableViewCell.
  • Stack view alignment and distribution set to fill.
  • UILabel content hugging priority 250 and compression resistance priority 750.
  • UIImageView content hugging priority 250 and compression resistance priority 749.
  • UIImageView aspect ratio 1:1.
  • UIImageView the same height as the UILabel.

All I get is this: enter image description here

Needless to say I have tried many different combinations but this is the best I get. I want the UIImageView (Facebook logo) to be the same height as 'Some text'.

I want this: enter image description here

Dan
  • 5,013
  • 5
  • 33
  • 59
  • Maybe the UIImageView and the UILabel are actually the same height, if the label is equal height to the StackView (that is equal to the Cell). UILabel centres text vertically. – vicegax Aug 05 '17 at 12:25
  • Yeah, the UILabel ends up stretching to be the same height as the UIImageView. I coloured the background of the UILabel grey to show that. I want the UILabel to stay to its intrinsic height. – Dan Aug 05 '17 at 12:31
  • You need to do it programatically, here a post on how to know the height of a `UILabel` according to the text it displays and the width it has to display it: https://stackoverflow.com/questions/27374612/how-do-i-calculate-the-uilabel-height-dynamically – vicegax Aug 05 '17 at 12:37

1 Answers1

13

Your label grows as the image grows, but you want the opposite behaviour. You can control this over the content compression resistance priority and the content hugging priority. You should set the vertical content hugging priority of the label to required. This will disallow, that the label is getting larger than its natural height. Set the vertical content compression resistance priority of the image and probably its horizontal pendant to low, which will allow the image to shrink to the labels height.

clemens
  • 16,716
  • 11
  • 50
  • 65
  • 2
    That worked. I set vertical compression resistance priority of the label to 1000 and compression resistance priority of the image to 250. Thank you! – Dan Aug 05 '17 at 12:56
  • 2
    Thanks so much. This is brilliant! + 10 if I could. – coolcool1994 Jan 11 '20 at 14:38