Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
550 views
in Technique[技术] by (71.8m points)

objective c - How to get UIView hierarchy index? (i.e. the depth in between the other subviews)

From UIView docs:

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

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...