How to set iPhone UIView z index?
I want to move one view on top of another, how can I know the z index of the view, and how to move on to top?
Solution 1:
You can use the zPosition
property of the view's layer (it's a CALayer
object) to change the z-index of the view.
theView.layer.zPosition = 1;
As Viktor Nordling added, "big values are on top. You can use any values you want, including negative values." The default value is 0.
You need to import the QuartzCore framework to access the layer. Just add this line of code at the top of your implementation file.
#import "QuartzCore/QuartzCore.h"
Solution 2:
UIView
siblings are stacked in the order in which they are added to their superview. The UIView
hierarchy methods and properties are there to manage view order. In UIView.h:
@property(nonatomic,readonly) UIView *superview;
@property(nonatomic,readonly,copy) NSArray *subviews;
- (void)removeFromSuperview;
- (void)insertSubview:(UIView *)view atIndex:(NSInteger)index;
- (void)exchangeSubviewAtIndex:(NSInteger)index1 withSubviewAtIndex:(NSInteger)index2;
- (void)addSubview:(UIView *)view;
- (void)insertSubview:(UIView *)view belowSubview:(UIView *)siblingSubview;
- (void)insertSubview:(UIView *)view aboveSubview:(UIView *)siblingSubview;
- (void)bringSubviewToFront:(UIView *)view;
- (void)sendSubviewToBack:(UIView *)view;
The sibling views are ordered back to front in the subviews
array. So the topmost view will be:
[parentView.subviews lastObject];
and bottom view will be:
[parentView.subviews objectAtIndex:0];
Like Kolin Krewinkel said, [parentView bringSubviewToFront:view]
will bring the view to the top, but this is only the case if the views are all siblings in the hierarchy.