Search code examples
iosswiftstatusbar

Add extra function when status bar is tapped


I want my navigation bar to unhide when the status bar is tapped. Currently it's only scrolling my webview to the top. Anybody knows how to get this working? The webview can still scroll to top, this function doesn't need to be removed.


Solution

  • Create a UIWindow with the same dimensions as your status bar, add a UIButton to the UIWindow, and position it on top of your status bar.

    import UIKit
    
    class ViewController: UIViewController {
    
        let statusbarWindow = UIWindow()
        let statusbarButton = UIButton()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Setup UIWindow
            statusbarWindow.frame = CGRectMake(0, 0,
                UIApplication.sharedApplication().statusBarFrame.size.width,
                UIApplication.sharedApplication().statusBarFrame.size.height)
            statusbarWindow.windowLevel = UIWindowLevelStatusBar
            statusbarWindow.makeKeyAndVisible()
    
            // Setup UIButton
            statusbarButton.frame = CGRectMake(0, 0,
                UIApplication.sharedApplication().statusBarFrame.size.width,
                UIApplication.sharedApplication().statusBarFrame.size.height)
            statusbarButton.backgroundColor = UIColor.clearColor()
            statusbarButton.addTarget(self, action: "statusbarButton:", forControlEvents: UIControlEvents.TouchUpInside)
            statusbarWindow.addSubview(statusbarButton)
        }
    
        func statusbarButton(sender:UIButton!) {
            // Scroll UIWebView to top
            yourWebView.scrollView.contentOffset = CGPoint(0,0)
            // Unhide nav bar here
        }
    

    Apple Docs: UIWindowLevel, makeKeyAndVisible.