safeAreaInset(edge:alignment:spacing:content:)
:
The modified view is inset by the height of content, from edge, with its safe area increased by the same amount.
It appears that SwiftUI's safeAreaInset
is not imported into UIKit's safe area:
ZStack {
Color.black
UIKitView()
}
.ignoresSafeArea(edges: .top)
.safeAreaInset(edge: .top) {
Text("TOP")
.frame(minHeight: 200)
.background(Color.cyan.opacity(0.5))
}
In this example, both the black
view and the UIKitView
are laid out the same - they ignore both the safeAreaInset:top
and the status bar.
The question is: how can the UIKitView
learn about the safe area in play?
Consider the following:
struct UIKitView: UIViewControllerRepresentable {
func makeUIViewController(context: Context) -> some UIViewController { ViewController() }
func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {}
class ViewController: UIViewController {
let bgView = UILabel()
let safeView = UILabel()
override func viewDidLoad() {
bgView.backgroundColor = .red.withAlphaComponent(0.5)
self.view.addSubview(bgView)
safeView.backgroundColor = .green.withAlphaComponent(0.5)
self.view.addSubview(safeView)
}
override func viewWillLayoutSubviews() {
self.bgView.frame = self.view.bounds
self.safeView.frame = self.view.safeAreaLayoutGuide.layoutFrame
}
}
}
We now see two layers generated by the UIKitView
, one that represents the full frame of the view (red
), and one that is limited to the known safe area (green
).
What is clear now is that UIKit's safe area is constrained by the status bar, but NOT by the safeAreaInset:top
. This is surprising – how can we learn about the full top safe area in play and correctly adjust the green view to accommodate the content placed manually above it?