开发者

Xcode - insertSubview:atIndex: not working as I expected it to

开发者 https://www.devze.com 2023-04-03 15:00 出处:网络
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

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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号