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