Reputation: 2189
I've been trying to use insertSubview:atIndex:
to insert a subview under another one. The problem is that most of the time it's not the view with the higher index that is above, but the view that was added last. I noticed that this works fine if I pick indexes 0 and 1 but in my case one view needs to be at least at the index 12 and the other one needs to be above.
Here is some code as an example:
UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, 100, 100, 100)];
label.text=@"LABEL";
[label setBackgroundColor:[UIColor whiteColor]];
[self.view insertSubview:label atIndex:13];
UIButton *btn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
btn.frame=CGRectMake(20, 100, 100, 100);
[btn setBackgroundColor:[UIColor whiteColor]];
[self.view insertSubview:btn atIndex:12];
I know I could insert the label after the button but that wouldn't solve the problem in my case.
What am I doing wrong?
Thank you in advance for your help.
Upvotes: 1
Views: 4012
Reputation: 57149
It doesn’t work like the CSS z-index
—if a view has k
subviews, inserting a view at any index higher than k
will have the same effect as adding it at index k
, or, in other words, adding it as the last (frontmost) subview. The subviews are maintained as a continuous list, not an arbitrarily-indexed array. In your case, you probably don’t have 14 subviews to start out with, so inserting one view at 13 and another at 12 isn’t having the effect you want.
Upvotes: 5