Dismiss the Keyboard in Swift via hitTest

1.1k views Asked by At

My code inside a UIView Class that contains a UITextField named titleInput:

override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
    // Code to Dismiss the Keyboard when Pressed Outside Text Field
    if !titleInput.pointInside(point, withEvent: event) {
        endEditing(true)
    }
    
    // Return Original hitTest Result as Usual
    return super.hitTest(point, withEvent: event)
}

I am experiencing a strange bug. When I first start the app, everything works as expected, touching outside the titleInput dismisses the keyboard. However, it brakes if I switch to a different app, and than come back to this app. After coming back to the app, clicking on the keyboard also dismisses the keyboard. Makes it difficult to type :)

Any idea why this is happening, and why it ONLY starts to happen after switching away from the app and then coming back to it? Also, is there a better way to do this same thing.

2

There are 2 answers

1
Patrick Zawadzki On

I would recommended doing it this way instead of what you are trying. This will just dismiss the keyboard when the enter/return key is pressed. I realize it is in Obj-C however the method calls are almost identical.

0
membersheep On

I usually do just this

override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
    view.endEditing(true)
    super.touchesBegan(touches, withEvent: event)
}