Created
October 27, 2022 21:30
-
-
Save colejd/04259a7087d3a7a6578e3da25ecdb1a5 to your computer and use it in GitHub Desktop.
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
/** | |
Adapted from here: | |
https://www.vadimbulavin.com/how-to-move-swiftui-view-when-keyboard-covers-text-field/ | |
Use these publishers to know when the keyboard is about to hide or show. | |
As an example, you can use this to scroll a ScrollView automatically after | |
the keyboard shows, using the timing information provided here. | |
*/ | |
import Combine | |
import SwiftUI | |
extension Publishers { | |
static var keyboardWillChange: AnyPublisher<(height: CGFloat, animationDuration: TimeInterval), Never> { | |
let willShow = NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification) | |
.map { | |
(height: $0.keyboardHeight, animationDuration: $0.keyboardAnimationDuration) | |
} | |
let willHide = NotificationCenter.default.publisher(for: UIApplication.keyboardWillHideNotification) | |
.map { | |
(height: CGFloat(0), animationDuration: $0.keyboardAnimationDuration) | |
} | |
return MergeMany(willShow, willHide) | |
.eraseToAnyPublisher() | |
} | |
} | |
extension Notification { | |
var keyboardHeight: CGFloat { | |
return (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.height ?? 0 | |
} | |
var keyboardAnimationDuration: TimeInterval { | |
return (userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval) ?? 0 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment