Created
November 14, 2019 00:23
-
-
Save cowlibob/ef4de21a825aa4199686cd66d960e01b to your computer and use it in GitHub Desktop.
SwiftUI - Modify layout while keyboard is open
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
// | |
// AdaptsToSoftwareKeyboard.swift | |
// Originally from https://stackoverflow.com/questions/56716311/how-to-show-complete-list-when-keyboard-is-showing-up-in-swiftui/58402607#58402607 | |
import Combine | |
import SwiftUI | |
struct AdaptsToSoftwareKeyboard: ViewModifier { | |
@State var currentHeight: CGFloat = 0 | |
func body(content: Content) -> some View { | |
content | |
.padding(.bottom, self.currentHeight) | |
.edgesIgnoringSafeArea(self.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: \.self.currentHeight, on: self) | |
} | |
} | |
// Example Usage | |
ScrollView { | |
// ... | |
}.modifier(AdaptsToSoftwareKeyboard()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment