Search code examples
iosautolayoutnslayoutconstraintios-autolayoutuistackview

iOS 10 square UIIMageView in Stackview breaks Autolayout when hidden


I have a UITableViewCell with something I thought was a pretty straight forward layout. The main content is a UIStackView (horizontal). In it I have UIImageView and two UILabels. On the UIImageView I have 2 constraints. One is an aspect ratio of 1:1 to make it square and the other is a height constraint to 55 points. The UIStackView is pinned to all sided of the cells contentView.

Now when I don't have an UIImage to display in the UIImageView, I simply call imageView.isHidden = true and the UIStackView hides the image. At the same time, on the Console I see AutoLayout breaking. It's telling me that it cannot satisfy the height of 55 together with the width of 0.

Well makes sense because due to the aspect ratio, the UIImageView wants to have a width of 55 as well. However, on the device itself I don't see any weird glitches. It exactly behaves as I would expect it.

So the question is

Is this a bad thing and how would I solve this with the least amount of code?

By the way, I'm using a dynamic height self sizing UITableView and let AutoLayout determine the height of my cells. It might happen that the UIImageView is the only content of the cell.


Solution

  • It's not a bug StackView Adds constraint to it's arrangedSubviews. when you call the hide on your view which in your case is the imageView. stackView tries to set the height Constraint to 0 but the Height constraint that you have added conflicts with the one which was added by stackView.

    you can change the Priority of the height constraint to something less than 1000 it will fix the conflicting issue