获取对iOS应用程序中最顶层视图/窗口的引用 [英] Getting reference to the top-most view/window in iOS application

查看:706
本文介绍了获取对iOS应用程序中最顶层视图/窗口的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个可重用的框架,用于在iOS应用程序中显示通知。我希望将通知视图添加到应用程序中其他所有内容的顶部,有点像UIAlertView。当我初始化侦听NSNotification事件并在响应中添加视图的管理器时,我需要获得对应用程序中最顶层视图的引用。这就是我现在所拥有的:

I'm creating a reusable framework for displaying notifications in an iOS application. I'd like the notification views to be added over the top of everything else in the application, sort of like a UIAlertView. When I init the manager that listens for NSNotification events and adds views in response, I need to get a reference to the top-most view in the application. This is what I have at the moment:

_topView = [[[[UIApplication sharedApplication] keyWindow] subviews] lastObject];

这适用于任何iOS应用程序,还是更安全/更好的方式来获得顶视图?

Would this work for any iOS application or is their a safer/better way to get the top view?

推荐答案

通常这会给你顶视图,但不保证它对用户可见。它可能在屏幕外,具有0.0的alpha值,或者可能具有0x0的大小。

Usually that will give you the top view, but there's no guarantee that it's visible to the user. It could be off the screen, have an alpha of 0.0, or could be have size of 0x0 for example.

也可能是keyWindow没有子视图,所以你应该先测试一下。这是不寻常的,但并非不可能。

It could also be that the keyWindow has no subviews, so you should probably test for that first. This would be unusual, but it's not impossible.

UIWindow是UIView的子类,因此如果您想确保用户可以看到您的通知,您可以添加它直接使用 addSubview:直接到keyWindow,它将立即成为最顶层的视图。我不确定这是不是你想要做的。 (根据你的问题,看起来你已经知道了。)

UIWindow is a subclass of UIView, so if you want to make sure your notification is visible to the user, you can add it directly to the keyWindow using addSubview: and it will instantly be the top most view. I'm not sure if this is what you're looking to do though. (Based on your question, it looks like you already know this.)

这篇关于获取对iOS应用程序中最顶层视图/窗口的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆