Using constraints in custom CollectionViewCell doesn't work

I am trying to use a CollectionViewCell with a StackView inside. As long as I don't add constraints, everything seems to work just fine, only the stack view isn't aligned. As soon as I add constraints, an error occurs due to missing constraints, but clicking on the "add missing constraints" button doesn't do anything. I solved my problem by adding a view to the cell and put the StackView inside, but I don't understand why it doesn't work without the view.

Replies

There are a couple of things to think about here:


— Xcode has a bug where it doesn't clear a constraint error after the necessary constraint has been added. When it seems to be complaining unnecessarily (e.g. when asking it to add missing constraints and it does nothing), it's worth closing the project and re-opening, to see if the errors are still there.


— Stack views can be a bit tricky, because by default they don't need any constraints at all. When you start adding constraints, you disable the default behavior, and you might need to add more constraints in places you didn't need them before. You should think about whether you have enough constraints between the stack view and its superview (or sibling view), as well as between the stack view and its subviews — the views that are stacked together.


But, adding sufficient constraints remains something of a mystery, so any solution that works is a good thing. 🙂