Skip to content

Instantly share code, notes, and snippets.

@cowlibob
Created November 14, 2019 00:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cowlibob/ef4de21a825aa4199686cd66d960e01b to your computer and use it in GitHub Desktop.
Save cowlibob/ef4de21a825aa4199686cd66d960e01b to your computer and use it in GitHub Desktop.
SwiftUI - Modify layout while keyboard is open
//
// 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