Skip to content

Instantly share code, notes, and snippets.

@steipete
Last active October 21, 2024 10:03
Show Gist options
  • Save steipete/da72299613dcc91e8d729e48b4bb582c to your computer and use it in GitHub Desktop.
Save steipete/da72299613dcc91e8d729e48b4bb582c to your computer and use it in GitHub Desktop.
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)
}
}
}
@vBoykoGit
Copy link

vBoykoGit commented Oct 9, 2020

Don't forget to add , ignoreSafeArea: true in your UIHostingController initializer.

@triage
Copy link

triage commented Dec 27, 2020

THANK YOU for this

@nikndr
Copy link

nikndr commented Jan 12, 2021

Man, you just saved my day. Thank you!

@schwjustin
Copy link

Thank you! Also, as @vBoykoGit mentioned, don't forget to add ignoreSafeArea: true!

@sfunke
Copy link

sfunke commented Nov 23, 2021

Yes, awesome, thank you! But is this safe to ship to the App Store or might the app get rejected?

@matejmolnar
Copy link

Thank you! @sfunke I've gotten multiple app versions approved with this snippet in the codebase, so it shouldn't be a problem.

@Majkitos
Copy link

Thank you, this is awesome 🔥

@freak4pc
Copy link

The fact this is still useful after 5 months is terrible. The fact this is working is wonderful :)
Thanks Peter 🙏

@esnssr
Copy link

esnssr commented Apr 21, 2024

i owe you a cookie ❤️

@PandaXZhang
Copy link

good job

@runningJoey
Copy link

does this also works for keyboard avoidance that a textFiled in a swiftUI sheet?
Waiting your response and really appreciate it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment