简体   繁体   中英

Objective-C Auto Adjust Subviews

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!

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

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.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM