ios,  swift,  auto-layout

Setting height constraint for a view in a cell

We needed a collection view cell that contained an image view and a label.

Setting height constraint for a view in a cell

We needed a collection view cell that contained an image view and a label. The image view had a constant height of 200 and was anchored to the left, right, and the top. The label was supposed to take the space unused by the image view and was anchored to the left, right, and the bottom. The top of the label was anchored to the bottom of the image view.

While the cell was displayed correctly an error Unable to simultaneously satisfy constraints. was outputted in the console. It looked like the auto layout was not happy about the height constraint of the image view.

It was not easy to infer what exactly was causing the height constraint to fail. The first hint came from a constraint named UIView-Encapsulated-Layout-Height that was set to 50. Apparently the cell tried to satisfy all the constraints before calling layoutSubviews when it is height was still 50.

Setting the priority of height anchor of the image view to 999 solved the problem.

let constraint = imageView.heightAnchor.constraint(equalToConstant:  200)
constraint.priority = 999

Subscribe to The infinite monkey theorem

Get the latest posts delivered right to your inbox