如何使UIView总是出现在前面?

目前我有一个包含一些控件的UIView。 然后,我有一些图像,我编程添加到视图显示为animation。 目前在我的游戏循环的每个间隔结束时,我不得不通知控制器将UIView控件移到前面,否则图像将出现在它的顶部。 有没有一种成本更低的方法使其始终保持在最前端。

目前我在游戏循环结束时有以下几点:

[self.view bringSubviewToFront:myControlView]; 

当游戏启动时我能做这样的事吗?

 myControlView.alwaysOnTop = true; 

而不是使用-addSubview:插入图像,使用-insertSubview:belowSubview:并传递你的UIView作为第二个参数:

 [self.view insertSubview:myImage belowSubview:myControlView]; 

请注意,为了类似的目的,您还可以访问方法-insertSubview:aboveSubview:-insertSubview:atIndex:

Objective-C的

 #import <QuartzCore/QuartzCore.h> myAlwaysOnTopView.layer.zPosition = MAXFLOAT; 

Swift 2

 myAlwaysOnTopView.layer.zPosition = .max 

Swift 3

 myAlwaysOnTopView.layer.zPosition = .greatestFiniteMagnitude 

这个解决scheme更好,特别是如果你希望你的视图始终处于最佳状态,不pipe在其后面添加了哪些视图。 只需使用addSubview:添加任何其他视图addSubview:它将始终保持在最前面。

另一种select是将您的视图放在另一个具有较高windowLevel的UIWindow中。 从Flipboard FLEX或我的简化派拉蒙学习

 Manager.action = { print("action touched") } Manager.show() 

看看如何select适当的windowLevel和处理触摸的FLEXWindow

 - (id)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if (self) { self.backgroundColor = [UIColor clearColor]; // Some apps have windows at UIWindowLevelStatusBar + n. // If we make the window level too high, we block out UIAlertViews. // There's a balance between staying above the app's windows and staying below alerts. // UIWindowLevelStatusBar + 100 seems to hit that balance. self.windowLevel = UIWindowLevelStatusBar + 100.0; } return self; } - (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event { BOOL pointInside = NO; if ([self.eventDelegate shouldHandleTouchAtPoint:point]) { pointInside = [super pointInside:point withEvent:event]; } return pointInside; } 

要使子视图移动到所有其他当前子视图的后面,请使用view.sendSubviewToBack(yourSubview)