Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

OS X Cocoa Auto Layout hidden elements

I am trying to use the new Auto Layout in Lion because it seems quite nice. But I can not find good information about how to do things. For example:

I have two labels:

+----------------+ | +------------+ | | + label 1    | | | +------------+ | |                | | +------------+ | | | label 2    | | | +------------+ | +----------------+ 

but the first label gets not always populated with content, sometimes there ist just no content for it. What I would like to do is to automatically show the label 2 where label 1 would be when it would have content.

+----------------+ | +------------+ | | + label 2    | | | +------------+ | |                | |                | |                | |                | +----------------+ 

What constrains would I have to add so it works automatically with autolayout? I understand that I could just code everything, but I have about 30 such labels and images and buttons of different styles and shapes which are all optional and I don't want to add hundrets of lines of code when it could work automatically quite nice too.

If it does not work then I will just use a WebView and do it with HTML and CSS.

like image 586
Jeena Avatar asked Oct 27 '11 20:10

Jeena


1 Answers

This is possible with auto layout, but doesn't exactly scale well.

So, taking your example, let's say you have label A, and label B (or button or anything else really). First start by adding a top constraint to the superview for A. Then a vertical spacing constraint between A and B. This is all normal so far. If you were to remove A at this point, B would have ambiguous layout. If you were to hide it, it would still occupy it's space including the space between the labels.

Next you need to add another constraint from B, to the top of the superview. Change the priority on this to be lower than the others (say 900) and then set it's constant to be standard (or other smaller value). Now, when A is removed from it's superview, the lower priority constraint will kick in and pull B towards the top. The constraints look something like this:

Interface Builder screenshot

The issue comes when you try to do this with a long list of labels.

like image 138
David Beck Avatar answered Oct 02 '22 11:10

David Beck