Here is a snippet that observes NotificationCenter
notifications related the keyboard, and changes the height of a spacer view based on the computed keyboard height.
import Combine
struct ExampleView: View {
@State var keyboardHeight: CGFloat = 0
var cancellables: Set<AnyCancellable> = []
init() {
NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)
.merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillHideNotification))
.compactMap({ notification in
guard let keyboardFrameValue: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return nil }
let keyboardFrame = keyboardFrameValue.cgRectValue
// If the rectangle is at the bottom of the screen, set the height to 0.
if keyboardFrame.origin.y == UIScreen.main.bounds.height {
return 0
} else {
// Adjust for safe area
return keyboardFrame.height - (UIApplication.shared.windows.first?.safeAreaInsets.bottom ?? 0)
}
})
.assign(to: \.keyboardHeight, on: self)
.store(in: &cancellables)
}
var body: some View {
VStack {
// Your content here
Spacer()
.frame(height: keyboardHeight)
}
}
}
I wrote a Swift package that handles this for you. It exposes a KeyboardObservingView
that wraps your content.
It's available here: https://github.com/nickffox/KeyboardObserving
You would use it like this:
var body: some View {
KeyboardObservingView {
List {...}
TextField("Placeholder", text: .constant(""))
.frame(minHeight: 30)
.cornerRadius(8.0)
.padding(10)
.background(Color.blue)
}
}
Here's an image of the package in use:
demo