Last active
October 23, 2020 04:22
-
-
Save perlguy99/4f74c3ee7073921123c0df151ae7fe51 to your computer and use it in GitHub Desktop.
SwiftUI Keyboard Aware Modifier
This file contains 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
// | |
// 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()) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My own copyright line came from Xcode. I'll remove it.