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

查看:18
本文介绍了获取对 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?

推荐答案

通常这会给你顶视图,但不能保证它对用户可见.例如,它可能不在屏幕上,alpha 为 0.0,或者大小可能为 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天全站免登陆