Forked from steipete/UIHostingController-Keyboard.swift
Created
September 24, 2021 18:38
-
-
Save tiagobbraga/69e19505c914b2ee9d8b9d3ae6ceb3a1 to your computer and use it in GitHub Desktop.
Disable Keyboard Interaction with UIHostingController. https://steipete.com/posts/disabling-keyboard-avoidance-in-swiftui-uihostingcontroller/
This file contains 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
extension UIHostingController { | |
convenience public init(rootView: Content, ignoreSafeArea: Bool) { | |
self.init(rootView: rootView) | |
if ignoreSafeArea { | |
disableSafeArea() | |
} | |
} | |
func disableSafeArea() { | |
guard let viewClass = object_getClass(view) else { return } | |
let viewSubclassName = String(cString: class_getName(viewClass)).appending("_IgnoreSafeArea") | |
if let viewSubclass = NSClassFromString(viewSubclassName) { | |
object_setClass(view, viewSubclass) | |
} | |
else { | |
guard let viewClassNameUtf8 = (viewSubclassName as NSString).utf8String else { return } | |
guard let viewSubclass = objc_allocateClassPair(viewClass, viewClassNameUtf8, 0) else { return } | |
if let method = class_getInstanceMethod(UIView.self, #selector(getter: UIView.safeAreaInsets)) { | |
let safeAreaInsets: @convention(block) (AnyObject) -> UIEdgeInsets = { _ in | |
return .zero | |
} | |
class_addMethod(viewSubclass, #selector(getter: UIView.safeAreaInsets), imp_implementationWithBlock(safeAreaInsets), method_getTypeEncoding(method)) | |
} | |
if let method2 = class_getInstanceMethod(viewClass, NSSelectorFromString("keyboardWillShowWithNotification:")) { | |
let keyboardWillShow: @convention(block) (AnyObject, AnyObject) -> Void = { _, _ in } | |
class_addMethod(viewSubclass, NSSelectorFromString("keyboardWillShowWithNotification:"), imp_implementationWithBlock(keyboardWillShow), method_getTypeEncoding(method2)) | |
} | |
objc_registerClassPair(viewSubclass) | |
object_setClass(view, viewSubclass) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment