Skip to content

Instantly share code, notes, and snippets.

@perlguy99
Last active October 23, 2020 04:22
Show Gist options
  • Save perlguy99/4f74c3ee7073921123c0df151ae7fe51 to your computer and use it in GitHub Desktop.
Save perlguy99/4f74c3ee7073921123c0df151ae7fe51 to your computer and use it in GitHub Desktop.
SwiftUI Keyboard Aware Modifier
//
// KeyboardAwareModifier.swift
// KeyboardTest
//
import SwiftUI
import Combine
struct KeyboardAwareModifier: ViewModifier {
@State private var keyboardHeight: CGFloat = 0
private var keyboardHeightPublisher: AnyPublisher<CGFloat, Never> {
Publishers.Merge(
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.compactMap { $0.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect }
.map { $0.height },
NotificationCenter.default
.publisher(for: UIResponder.keyboardWillHideNotification)
.map { _ in CGFloat(0) }
).eraseToAnyPublisher()
}
func body(content: Content) -> some View {
content
.padding(.bottom, keyboardHeight)
.onReceive(keyboardHeightPublisher) { self.keyboardHeight = $0 }
}
}
extension View {
func keyboardAwarePadding() -> some View {
ModifiedContent(content: self, modifier: KeyboardAwareModifier())
}
}
@perlguy99
Copy link
Author

My own copyright line came from Xcode. I'll remove it.

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