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?
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]
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.
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];
Top view on top window. Just to be complete. As already pointed out in the question:
UIView *topView = [[topWindow subviews] lastObject];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With