iOS Open Source : UIView Category to Manage Z-Order of Views

This edition of iOS Open Source is a category extension to the UIView class that adds code to facilite managing UIView hieracrhies. The code offers a straight-forward means to manage where views appear in a subview hierachy. If you are unfamiliar with Objective-C categories, head over here: Working with Categories.

The code below shows the category definition and the methods defined in UIView+Hierarchy.h.

@interface UIView (Hierarchy)
 
-(int)getSubviewIndex;
 
-(void)bringToFront;
-(void)sendToBack;
 
-(void)bringOneLevelUp;
-(void)sendOneLevelDown;
 
-(BOOL)isInFront;
-(BOOL)isAtBack;
 
-(void)swapDepthsWithView:(UIView*)swapView;
 
@end

Once you create a class with a UIView and import UIView+Hierarchy.h you can easily request views to be moved to forward and backward in the hierachy as well as inquire if a view is at the front or back.

UIView* greenView;
 
[greenView bringOneLevelUp];
[greenView sendOneLevelDown];
if ([greenView isInFront] == YES) 
  ...

Credits

This category and sample project was written by Marin Todorov. Thanks Marin for making this code open source.

Source Code Download

The UIView Category source code and an Xcode project to exercise the code can be downloaded here: ViewSortDemo.zip

Suggestions For Open Source Projects?

If you have written, worked with or otherwise know of an interesting open source project, one that is focused on iOS development, feel free to send me a note. Even a simple class/category that offers something useful is welcome. Contact me with ideas and suggestions.

  1. I’ve wondered all along why Apple didn’t support Z-Ordering more elegantly from the start.

    It’s a handy category, though not quite what I expected when I first saw this post. I was hoping for arbitrary z-coordinate assignment and ordering based on those coordinates, i.e. the view with v1.z = 28.5, when inserted, gets inserted below v2.z = 19.8 and above v3.z = 39.0. I suppose it wouldn’t take too much more to add that functionality, though it would take more than a category, as you would be adding a property to the views being ordered.

    • Thanks Michelle. If you get time to put something like you suggest together, please let me know and I’ll get it mentioned here for others to check out as well.

  2. Hi John, thanks for publishing this! I always enjoy your rss and I’m glad to contribute :)

    @Michelle Yes, true z-order property is definitely a good idea! When I was researching about z-order of the UIView I didn’t find any info in the Apple docs, so when realized subviews index is the z-order just wanted to pack it so others can make use of that fact, so yeah it’s pretty simple

  3. someview.layer.zPosition = 1 (float value indicating order)

Comments are closed.