Last active
September 25, 2024 12:45
-
-
Save karambirov/4523a8109dd1b349a9a13e5ceee87c1e to your computer and use it in GitHub Desktop.
How to ignore safe area in UIHostingController
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 SwiftUI | |
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, | |
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) | |
) | |
} | |
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