iOS+iPadOS keyboard-aware helpers for SwiftUI.
The SwiftUI API does not (currently) provide any native way to respond to the system keyboard when running on iOS/iPadOS. This library translates keyboard events from the UIKit world (via keyboard-related Notifications) into easy-to-integrate SwiftUI extensions.
Add the KeyboardObserver Swift Package as a dependency:
File > Swift Packages > Add Package Dependency, then provide the git URL when prompted.
Add an entry to dependencies in your package manifest (Package.swift)
dependencies:[.package(url:"git@github.com:timdonnelly/KeyboardObserver.git", from:"0.1.2")]Be sure to import the module wherever you will be using it:
import KeyboardObserverThis is the simplest way to make UI keyboard-aware: it automatically insets all children when the keyboard is visible. Layout changes are animated to match the system keyboard.
VStack{Text("Hello, world!")TextField("Title", text: $text)}.frame(maxWidth:.infinity, maxHeight:.infinity).avoidingKeyboard()The binding provided to observingKeyboard(_:) will be assigned with an animation that matches the system keyboard.
import KeyboardObserver
structMyView:View{@Stateprivatevarstate=KeyboardState()varbody:someView{GeometryReader{ proxy inVStack{Text("Hello, world!")TextField("Title", text:self.$text)}.frame(maxWidth:.infinity, maxHeight:.infinity).padding(.bottom,self.state.height(in: proxy))}.observingKeyboard($state)}}The provided closure is invoked to manually respond to keyboard changes. An Animation value is included that can be used to to drive custom transitions.
import KeyboardObserver
structMyView:View{varbody:someView{Text("HelloWorld").onKeyboardChange{ state, animation inself.handleKeyboardChange(newState: state, animation: animation)}}privatefunc handleKeyboardChange(newState:KeyboardState, animation:Animation?){
// Handle keyboard changes here (`animation` will be non-nil if the keyboard change is animated)
}}