将子视图置于最前面的问题?

16

你好,我有一个父视图和多个子视图。当我在父视图中使用[self bringSubviewToFront:childview]时,它可以正常工作。但是,当我在子视图中添加了孙子视图后,在父视图中使用[self bringSubviewToFront: grandchildview]就不能正常工作了。请问有什么帮助吗?

2个回答

64

-[UIView bringSubviewToFront:] 方法只对直接子视图起作用,不包括孙子视图。请记住,视图层次结构是一棵树,通常情况下,一个视图只知道它的“父视图”(或者超级视图)和它的直接“子视图”(或者子视图)。你需要这样做:

// First, get the view embedding the grandchildview to front.
[self bringSubviewToFront:[grandchildview superview]];
// Now, inside that container view, get the "grandchildview" to front. 
[[grandchildview superview] bringSubviewToFront:grandchildview];

递归地完成这个任务会更好。 - Pizzaiola Gorgonzola
1
@PizzaiolaGorgonzola 对于任意嵌套级别,递归方法是可行的。但对于这个简单的情况来说,这样做会过度杀伤力。 - DarkDust
谢谢,我已经为这个问题苦苦挣扎了一段时间。 - Supertecnoboff
太棒了,代码非常干净且运行良好!非常感谢 :) - Jack Solomon

1

我的贡献是使用经过检查的解决方案的Swift版本。

self.bringSubviewToFront(self.grandchildview.superview!)
self.grandchildview.superview!.bringSubviewToFront(self.grandchildview)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接