Skip to content

Commit 9706ae6

Browse files
committed
fix(ios): prevent SwiftUI filter content collapse
1 parent ad870da commit 9706ae6

1 file changed

Lines changed: 44 additions & 1 deletion

File tree

packages/react-native/ReactApple/RCTSwiftUI/RCTSwiftUIContainerView.swift

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,10 @@ import UIKit
1515
@objc public override init() {
1616
super.init()
1717
hostingController = UIHostingController(rootView: SwiftUIContainerView(viewModel: containerViewModel))
18-
guard let view = hostingController?.view else {
18+
guard let hostingController, let view = hostingController.view else {
1919
return
2020
}
21+
Self.disableSafeArea(for: hostingController)
2122
view.backgroundColor = .clear
2223
}
2324

@@ -77,6 +78,48 @@ import UIKit
7778
containerViewModel.contrastAmount = 1
7879
containerViewModel.hueRotationDegrees = 0
7980
}
81+
82+
private static func disableSafeArea(
83+
for hostingController: UIHostingController<SwiftUIContainerView>
84+
) {
85+
if #available(iOS 16.4, *) {
86+
hostingController.safeAreaRegions = []
87+
return
88+
}
89+
90+
// Keep the pre-16.4 fallback scoped to this hosting view instance instead
91+
// of changing SwiftUI's private hosting view class globally.
92+
guard let hostingView = hostingController.view,
93+
let viewClass = object_getClass(hostingView)
94+
else {
95+
return
96+
}
97+
98+
let subclassName = String(cString: class_getName(viewClass))
99+
.appending("_RCTIgnoresSafeArea")
100+
if let viewSubclass = NSClassFromString(subclassName) {
101+
object_setClass(hostingView, viewSubclass)
102+
return
103+
}
104+
105+
guard let subclassNameUtf8 = (subclassName as NSString).utf8String,
106+
let viewSubclass = objc_allocateClassPair(viewClass, subclassNameUtf8, 0),
107+
let method = class_getInstanceMethod(UIView.self, #selector(getter: UIView.safeAreaInsets))
108+
else {
109+
return
110+
}
111+
112+
let safeAreaInsets: @convention(block) (AnyObject) -> UIEdgeInsets = { _ in
113+
return .zero
114+
}
115+
class_addMethod(
116+
viewSubclass,
117+
#selector(getter: UIView.safeAreaInsets),
118+
imp_implementationWithBlock(safeAreaInsets),
119+
method_getTypeEncoding(method))
120+
objc_registerClassPair(viewSubclass)
121+
object_setClass(hostingView, viewSubclass)
122+
}
80123
}
81124

82125
class ContainerViewModel: ObservableObject {

0 commit comments

Comments
 (0)