I have a project where two horizontal Stack Views are packed in a (main) vertical Stack View. Each horizontal Stack View contains a button and a switch.
I set the leading and trailing constraint of the main StackView. The problem is that when the button´s title is too long the switch is pushed out of the screen limit.
Here is how it looks like in Interface Builder:
Below is how it looks like in an simulator:
There are no constraints between the button and a switch since every time I packed these elements in the horizontal Stack View all constraints are lost.
I created the constraints by specifying Constrain to margins:
I tried to find a solution here but I did not find it.
I am pretty lost, what do I do wrong ? Why does the switch go outside of the screen despite the constraints ? Do I miss something about what constraints are ?
In the first place, it looks like your buttons need to be labels. Buttons do not like to have multiple lines of content. If you need the label to be tappable for some reason, you can do that.
In the second place, you need to lower the label's (or button's) horizontal content compression resistance priority to 749, so that it is lower than that of the switch (which is 750 by default). That way, the two of them will not battle each other for position: the switch will win, and the label will allow itself to give ground even as its text becomes larger.
Having said that, I think you might be a lot happier with a different underlying interface. A stack view, and in particular stack views acting as similar rows embedded in a vertical stack view, doesn't seem like a good fit for what you are doing. Here's the same sort thing, done instead as a table view:
I think this is a much better way to achieve your goals. The table view doesn't have to look like a table view; in the screen shot above, the table view can't scroll, its cells can't be selected, and it has no cell separators. But the repetition of the cell consisting of a label and a switch is much more easily and flexibly achieved than what you're doing; it is trivial to expand what I'm doing to many more questions and switched, whereas what you are doing is not going to be easy or pleasant to scale up.