Created
October 16, 2019 17:27
-
-
Save nathanborror/0654a1ba701d1389705cbd35914a8d13 to your computer and use it in GitHub Desktop.
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
// https://stackoverflow.com/questions/56716311/how-to-show-complete-list-when-keyboard-is-showing-up-in-swiftui?noredirect=1&lq=1 | |
import SwiftUI | |
import Combine | |
struct AdaptToKeyboard: ViewModifier { | |
@State var currentHeight: CGFloat = 0 | |
func body(content: Content) -> some View { | |
content | |
.padding(.bottom, currentHeight) | |
.edgesIgnoringSafeArea(currentHeight == 0 ? Edge.Set() : .bottom) | |
.onAppear(perform: subscribeToKeyboardEvents) | |
} | |
private let keyboardWillOpen = NotificationCenter.default | |
.publisher(for: UIResponder.keyboardWillShowNotification) | |
.map { $0.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect } | |
.map { $0.height } | |
private let keyboardWillHide = NotificationCenter.default | |
.publisher(for: UIResponder.keyboardWillHideNotification) | |
.map { _ in CGFloat.zero } | |
private func subscribeToKeyboardEvents() { | |
_ = Publishers.Merge(keyboardWillOpen, keyboardWillHide) | |
.subscribe(on: RunLoop.main) | |
.assign(to: \.currentHeight, on: self) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment