TIMEX TIMEX - 5 months ago 66x
Swift Question

In Swift, how can I detect a tap on the status bar?

My status bar will never be hidden throughout my entire app. Is there a simple way to detect it when it is tapped?


Here is how I have solved this:

In your AppDelegate add the following:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    super.touchesBegan(touches, withEvent: event)
    let events = event!.allTouches()
    let touch = events!.first
    let location = touch!.locationInView(self.window)
    let statusBarFrame = UIApplication.sharedApplication().statusBarFrame
    if CGRectContainsPoint(statusBarFrame, location) {
        NSNotificationCenter.defaultCenter().postNotificationName("statusBarTouched", object: nil)

The you need to subscribe for this function, so in the class you want to add the touch event just add;

NSNotificationCenter.defaultCenter().addObserverForName("statusBarTouched", object: nil, queue: nil) { event in
     print("Touched status bar")

In viewDidload. If you would like to implement scroll to top when the status bar is touched, just add:

self.tableView!.setContentOffset(CGPointZero, animated: true)

In the NSNotificationCenter.defaultCenter() snippet.