Getting reference to the top-most view/window in iOS application

typeoneerror picture typeoneerror · Oct 2, 2010 · Viewed 105.4k times · Source

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];

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

Answer

samvermette picture samvermette · Oct 2, 2010

Whenever I want to display some overlay on top of everything else, I just add it on top of the Application Window directly:

[[[UIApplication sharedApplication] keyWindow] addSubview:someView]