views:

1301

answers:

1

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 ...

EDIT: Now that Brandon pointed out the order in the subviews array, I put together a UIView Category free for download providing few handy methods to handle the subviews hierarchy here: http://www.touch-code-magazine.com/uiview-layout-hierarchy-uiview-category-to-download/

+2  A: 

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
Brandon Bodnár
I was trying out this just before posting the question. The indexes in the subviews array stay the same :(
Ican Zilb
Really, cause my test show that the index in the subview array does change after a call to `bringSubviewToFront:`
Brandon Bodnár
You are perfectly correct Brandon, I have a view mapper which doesn't change the indexes; the subviews array on the other hand changes them. Thanks. However I should admit the docs are vague on how to get the index and whether the smaller indexes are on top or vice versa.
Ican Zilb
Haha. Yup, they are very vague, that is why I was not sure of the answer till I did a bunch of test. Turns out index 0 is back, index (# of views - 1) is the front, and the array is kept in proper order. I haven't see a reference document to support this though, so I hope that it does not change in later SDKs
Brandon Bodnár
Brandon, I put together a small category for managing the UIView's depth, I put a link to your site as attribution (url in the original question now) let me know if ok with u
Ican Zilb
Sure. I treat most of what I do as creative commons. no problem here, but thanks for asking.Thanks for making the category available to others.
Brandon Bodnár