如何获取 UIView 层次结构索引?(即其他子视图之间的深度) [英] How to get UIView hierarchy index? (i.e. the depth in between the other subviews)

查看:22
本文介绍了如何获取 UIView 层次结构索引?(即其他子视图之间的深度)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自 UIView 文档:

From UIView docs:

(void)insertSubview:(UIView *)view atIndex:(NSInteger)index

我可以在某个索引处插入 UIView 很棒,但是我找不到读取给定 UIView 的索引的方法.

It's great that I can insert a UIView at a certain index, but I cannot find a way to READ what index a given UIView has.

我需要检查 UIView 是在上面还是在后面...

I need to check whether the UIView is on top, or at the back ...

推荐答案

我几乎 100% 确定该索引与 superViews subviews 属性内的 subView 的索引相同.

I am almost 100% sure that the index is the same as the index of the subView inside the superViews subviews property.

UIView * superView = .... some view
UIView * subView = .... some other view
[superView insertSubview:subView atIndex:index];
int viewIndex = [[superView subviews] indexOfObject:subView];
// viewIndex and index should be the same

我刚刚用下面的代码测试了这个,它可以工作

I just tested this with the following code and it works

UIView* view1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
UIView* view2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
UIView* view3 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)];
[self.view insertSubview:view1 atIndex:1];
[self.view insertSubview:view2 atIndex:2];
[self.view insertSubview:view3 atIndex:3];

NSLog(@"%d", [[self.view subviews] indexOfObject:view1]); // Is 1
NSLog(@"%d", [[self.view subviews] indexOfObject:view2]); // Is 2
NSLog(@"%d", [[self.view subviews] indexOfObject:view3]); // Is 3

[self.view bringSubviewToFront:view1];
NSLog(@"%d", [[self.view subviews] indexOfObject:view1]); // Is end of array

[self.view sendSubviewToBack:view1];
NSLog(@"%d", [[self.view subviews] indexOfObject:view1]); // Is 0

这篇关于如何获取 UIView 层次结构索引?(即其他子视图之间的深度)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆