views:

145

answers:

2

I'm looking to write a method for an iPhone app that will auto adjust a UIViews's subviews Y values depending on the available space within that view. I'll try my best to explain without getting too confusing.

I have a Container view that is housing up to 3 Subviews. With in each subview is a button that removes the sub view from the container view, when the subview is removed i would like to adjust the remaining subviews to take up whatever space that has been opened by the removed subview.

Thanks in advance for any help!

+1  A: 

Well the first thing you need to do is signal your container that a subview has been removed.

Then you can take the height value of the view that was removed, divide it by the number of remaining subviews, and then expand the height of those remaining subviews.

Then you set your first remaining subview to Y coordinate 0, and the second (if there is one), to a Y coordinate of the first subviews height value

Jasconius
Thanks for the fast reply, it was helpful everything makes sense except i'm not looking to stretch the view i'm actually looking to only adjust the Y coordinates to move up, this will ensure that when i add subviews to the container the newest always ends up on the bottom of the parent view. Sorry i didn't make the more clear in my question.
Jealous Republic
A: 

One way is to make your wrapper view a custom UIView subclass. In that subclass, maintain a separate NSMutableArray of your subviews wherein each subview's array index corresponds to its position on the screen.

With this in place, you have a couple of options. One is to overide didAddSubview:. Based on the frame of the subview being added, you can determine the subview's position and insert reference to the subview at the appropriate index in your array.

A cleaner option is to implement your own custom method like this:

- (void)insertSubview:(UIView *)subview atPosition:(NSInteger)position;

where position is an index identifying which "slot" the subview should fill. You can set the frame for the subview explicitly within this method, along with any other subviews that are impacted by the insertion. Then insert the subview into your array at the corresponding index.

Finally, override willRemoveSubview:. In it you can use indexOfObject: on your array to find the position of the subview being removed. Then simply adjust the frames of all the subviews that follow it, and remove the subview from your array.

(One other alternative is to skip the array and just use the tag property to indicate the position of each subview. I don't like this option though. Using the tag property for anything always feels like a terrible hack to me.)

cduhn
Your the man! Thanks for taking the time to answer, i didn't even know i could do a quarter of the things you mentioned.
Jealous Republic