Creating custom notification iOS banner sliding over status bar
I’m working on a very big iOS project and recently I received a request from UI-UX team: in-app banner “like iOS notifications”. I got my solution by making an extension for UIViewController, in order to have a simple method that I can easily use in every ViewController of the app.
Great solution, right? And this is the result:
In every single view controller of my app I can use this to get the Banner:
showSimpleBanner(with: .success, and: "Title", and: "Message")The most simple way to achieve that: showSimpleBanner() is a method of UIViewController now, and I can call it everywhere. And I received compliments from UI-UX guys too 😇
But I have a problem. I simply add the Banner as a subview of the view controller. In this way, I don’t get exactly what I want: Banner does not overlays status bar. And although this is not a requirement, I really want to understand how to achieve that kind of overlay, like Apple does.
After a while, this is the result:
and today I want to share with you how I got it.
There are only two ways to have an UIView instance over status bar. The first is to hide status bar, but for a nice effect you should have a view that entirely cover the status bar. If you are in a situation like mine, you can’t simply hide the status bar. You have to create a new UIWindow.
Just to make things easy, we can say that UIWindow is a sort of container for the entire app you’re developing. Every single iOS app is automatically initialized by Xcode with one and only UIWindow, a keyWindow that you can get it in this way:
let keyWindow = UIApplication.shared.keyWindowFor more, visit official documentation here.
Apple says that UIWindow is useful to display additional content for your app, that’s the point. By creating our Banner without using a UIWindow, we just can’t get it as an external thing, because it is automatically created in the keyWindow, the UIWindow in which there’s also the entire app. By creating a new UIWindow, we are creating “another app”, that in this case is a Banner app 🤪
So, we first have to create our window for the Banner, in this way:

I strongly suggest to make it with the exactly same frame of the Banner you want to show because a window covers the entire view controller and if you make it bigger than the Banner, you won’t be able to tap the other elements of the screen.
With this initialization, you’ll have a new window that is hidden, for a first moment. When you’ll want to show it, you’ll have to do this:

For the source code, here: https://github.com/evicoli/NotificationBanner
That’s all! In this way you’ll have your Banner that covers status bar, like iOS notifications. I hope you’ve find this useful, bye! 👋
EDIT: 01/07/2019, it seems this thing doesn’t work with iOS 13. I’ll update if I’ll have news.
