This package give you the ability to observe changes to keyboard state using the KeyboardObservableObject type.
It also provides a KeyboardObservingView that adjusts its content to avoid the keyboard, and a .keyboardObserving() ViewModifier that adjusts the modified view to avoid the keyboard.
- iOS 13.0+
- Xcode 11+
- Swift 5.1+
This package can be installed using CocoaPods or Swift Package Manager.
Add the following line to your Podfile:
pod 'KeyboardObserving'
For more information about how to get started with CocoaPods, check out the CocoaPods website.
Add the following to your Package.swift file:
dependencies: [
.package(
url: "https://github.com/nickffox/KeyboardObserving.git", .branch:("master")
)
]
If you're using SPM through Xcode:
- Go to
File > Swift Packages > Add Package Dependency - Enter https://github.com/nickffox/KeyboardObserving
- Select the
branchoption, and type "master"
For more information about how to get started with the Swift Package Manager, check out the Official SPM website or the SPM project on GitHub.
Add the .keyboardObserving() ViewModifier to your custom SwiftUI view.
import KeyboardObserving
structYourView:View{varbody:someView{VStack{
// Your Content Here
}.keyboardObserving()}}In your SceneDelegate.swift file, add a Keyboard property, and add it to your scene's environment.
import KeyboardObserving
classSceneDelegate:UIResponder,UIWindowSceneDelegate{varwindow:UIWindow?
// A Keyboard that will be added to the environment.
varkeyboard=Keyboard()func scene(_ scene:UIScene, willConnectTo session:UISceneSession, options connectionOptions:UIScene.ConnectionOptions){
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Use a UIHostingController as window root view controller
iflet windowScene = scene as?UIWindowScene{letwindow=UIWindow(windowScene: windowScene)
window.rootViewController =UIHostingController(
rootView:YourRootView()
// Adds the keyboard to the environment
.environmentObject(keyboard))self.window = window
window.makeKeyAndVisible()}}}Add your view's content inside of a KeyboardObservingView .
import KeyboardObserving
structYourView:View{varbody:someView{KeyboardObservingView{
// Your content goes here!
}}}