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()) | |
} | |
} |
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
Between making your gists private and not providing attribution, I prefer the latter. The gist is useful. I wouldn't say anything if this was a verbatim copy of an answer from SO. Attribution would be cool, but that never happens, I know that. But adding your own copyright line? That's just unnecessary, no? Anyway, I didn't mean to discourage you from making your stuff public, I merely meant to encourage you to add attribution and remove invalid copyright line.