我想把一个视图移到另一个视图的上方,我怎么知道视图的z索引,以及如何移到顶部?


当前回答

[parentView bringSubviewToFront:view] ;

其他回答

UIView的兄弟姐妹是按照它们被添加到父视图的顺序堆叠的。UIView的层次结构方法和属性是用来管理视图顺序的。在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;

兄弟视图在子视图数组中由后往前排序。所以最上面的视图是:

[parentView.subviews lastObject];

底部视图将是:

[parentView.subviews objectAtIndex:0];

就像Kolin Krewinkel说的,[parentView bringSubviewToFront:view]将把视图带到顶部,但只有当视图在层次结构中都是兄弟姐妹时才会出现这种情况。

在你想要放到顶部的视图中… (迅速)

superview?.bringSubviewToFront(self)

或者用这个

- (void)insertSubview:(UIView *)view belowSubview:(UIView*)siblingSubview;

根据这里

如果你想通过XCode的Interface Builder来实现,你可以使用Editor->Arrangement下的菜单选项。在那里你会发现“发送到前面”,“发送到后面”,等等。

如果你正在使用cocos2d,你可能会看到[parentView bringSubviewToFront:view]的问题,至少它不适合我。我没有把我想要的视图放到前面,而是把其他视图放到后面,这样就成功了。

[[[CCDirector sharedDirector] view] sendSubviewToBack:((UIButton *) button)];