Skip to content

Instantly share code, notes, and snippets.

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 oalansari82/74df09af91b81da130810d5a4e7764aa to your computer and use it in GitHub Desktop.
Save oalansari82/74df09af91b81da130810d5a4e7764aa to your computer and use it in GitHub Desktop.
An example of using Combine to automatically adapt a SwiftUI scrollable view to accommodate an iOS onscreen keyboard
import SwiftUI
import Combine
struct AdaptsToSoftwareKeyboard: ViewModifier {
@State var currentHeight: CGFloat = 0
func body(content: Content) -> some View {
content
.padding(.bottom, currentHeight)
.edgesIgnoringSafeArea(.bottom)
.onAppear(perform: subscribeToKeyboardEvents)
}
private func subscribeToKeyboardEvents() {
NotificationCenter.Publisher(
center: NotificationCenter.default,
name: UIResponder.keyboardWillShowNotification
).compactMap { notification in
notification.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect
}.map { rect in
rect.height
}.subscribe(Subscribers.Assign(object: self, keyPath: \.currentHeight))
NotificationCenter.Publisher(
center: NotificationCenter.default,
name: UIResponder.keyboardWillHideNotification
).compactMap { notification in
CGFloat.zero
}.subscribe(Subscribers.Assign(object: self, keyPath: \.currentHeight))
}
}
import SwiftUI
struct KeyboardAwareScrollableView : View {
@ObjectBinding var venue: SomeDataModel
var body: some View {
// Apply to any view with an instrinsic scroll view – ScrollView, Form, List, etc
Form {
Section {
TextField($venue.name, placeholder: Text("Venue Name"))
}
Section(header: Text("Address")) {
TextField($venue.street, placeholder: Text("Street"))
TextField($venue.city, placeholder: Text("City"))
TextField($venue.country, placeholder: Text("Country"))
TextField($venue.postalCode, placeholder: Text("Postcode/ZIP"))
}
// etc.
}
.navigationBarTitle(Text("New venue"))
.modifier(AdaptsToSoftwareKeyboard()) // <-- apply the modifier here
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment