I feel like it\'s a fairly common paradigm to show/hide UIViews
, most often UILabels
, depending on business logic. My question is, what is the best
The solution of using a constant 0
when hidden and another constant if you show it again is functional, but it is unsatisfying if your content has a flexible size. You'd need to measure your flexible content and set a constant back. This feels wrong, and has issues if content changes size because of server or UI events.
I have a better solution.
The idea is to set the a 0 height rule to have high priority when we hide the element so that it takes up no autolayout space.
Here's how you do that:
1. set up a width (or height) of 0 in interface builder with a low priority.
Interface Builder won't yell about conflicts because the priority is low. Test the height behavior by setting the priority to 999 temporarily (1000 is forbidden to mutate programmatically, so we won't use it). Interface builder will probably now yell about conflicting constraints. You can fix these by setting priorities on related objects to 900 or so.
2. Add an outlet so you can modify the priority of the width constraint in code:
3. Adjust the priority when you hide your element:
cell.alertTimingView.hidden = place.closingSoon != true
cell.alertTimingWidth.priority = place.closingSoon == true ? 250 : 999