Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 322
typeoneerror Avatar asked Oct 01 '10 22:10

typeoneerror


2 Answers

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] 
like image 83
samvermette Avatar answered Oct 05 '22 17:10

samvermette


There are two parts of the problem: Top window, top view on top window.

All the existing answers missed the top window part. But [[UIApplication sharedApplication] keyWindow] is not guaranteed to be the top window.

  1. Top window. It is very unlikely that there will be two windows with the same windowLevel coexist for an app, so we can sort all the windows by windowLevel and get the topmost one.

    UIWindow *topWindow = [[[UIApplication sharedApplication].windows sortedArrayUsingComparator:^NSComparisonResult(UIWindow *win1, UIWindow *win2) {     return win1.windowLevel - win2.windowLevel; }] lastObject]; 
  2. Top view on top window. Just to be complete. As already pointed out in the question:

    UIView *topView = [[topWindow subviews] lastObject]; 
like image 22
an0 Avatar answered Oct 05 '22 16:10

an0