Created
August 29, 2018 22:03
-
-
Save RustyKnight/b67c76117ac6148d5b81dacc5ef8d3d0 to your computer and use it in GitHub Desktop.
Dismissible keyboard support for iOS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import UIKit | |
// I'm not a fan of this, but this will allow us to maintain state beyond the capabailities of the the extension API | |
fileprivate var cache = NSMapTable<UIViewController, UITapGestureRecognizer>(keyOptions: .weakMemory, valueOptions: .weakMemory) | |
extension UIViewController { | |
fileprivate var tapRecognizer: UITapGestureRecognizer? { | |
return cache.object(forKey: self) | |
} | |
fileprivate var isInstalled: Bool { | |
return tapRecognizer != nil | |
} | |
var dismissKeyboardOnTap: Bool { | |
set { | |
if newValue { | |
guard !isInstalled else { | |
return | |
} | |
let recognizer = UITapGestureRecognizer(target: self, action: #selector(hideKeyboardLater)) | |
recognizer.cancelsTouchesInView = false | |
view.addGestureRecognizer(recognizer) | |
cache.setObject(recognizer, forKey: self) | |
} else { | |
guard let recognizer = tapRecognizer else { | |
return | |
} | |
view.removeGestureRecognizer(recognizer) | |
cache.removeObject(forKey: self) | |
} | |
} | |
get { | |
guard cache.object(forKey: self) != nil else { | |
return false | |
} | |
return true | |
} | |
} | |
@objc private func hideKeyboardLater() { | |
DispatchQueue.main.async { | |
self.hideKeyboard() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Supports control to isolate which views will support the feature.
Tap gestures case the keyboard to be dismissed