Search code examples
iosuiviewuiscrollviewhittest

Swift 2 - hitTest function - fatal error found nil


I have a bottom bar UIView inside an UIScrollView with two buttons in it. I am using the function hitTest in order to enable user interaction just for the two buttons.

The code works only if I touch the bottom bar however, when I touch any other part of the screen the app crashes saying:

fatal error: unexpectedly found nil while unwrapping an Optional value (lldb)

class HelpBarViewClass: UIView {

    @IBOutlet var backPageBtn: UIButton!
    @IBOutlet var nextPageBtn: UIButton!

    override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {

        let subview: UIView = super.hitTest(point, withEvent: event)! // fatal error
        return subview == self.nextPageBtn || subview == self.backPageBtn ? subview :nil

    }

}

Why am I having this error?

UPDATE

Thanks to answer below the right code is:

class HelBarViewClass: UIView {

    @IBOutlet var backPageBtn: UIButton!
    @IBOutlet var nextPageBtn: UIButton!

    override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {

        let subview = super.hitTest(point, withEvent: event)
        return subview == self.nextPageBtn || subview == self.backPageBtn ? subview : nil

    }

}

Solution

  • Seems obvious: super.hitTest returned nil but you force-unwrapped it. Don't do this.