Skip to content

Instantly share code, notes, and snippets.

@michzio
Last active May 4, 2020 17:24
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 michzio/c95d46ec95aa76ee8731be391c936126 to your computer and use it in GitHub Desktop.
Save michzio/c95d46ec95aa76ee8731be391c936126 to your computer and use it in GitHub Desktop.
final class KeyboardAvoider : ObservableObject {
private var _rects = [Int: CGRect]() {
didSet {
print("Keyboard Avoider rects changed: \(_rects.count)")
}
}
var rects: [Int: CGRect] {
set {
guard keyboardRect == .zero else {
print("Warning: Keyboard Avoider changing rects while keyboard is visible.")
return
}
_rects = newValue
}
get {
_rects
}
}
var editingField : Int = -1 {
didSet {
updateSlideSize()
}
}
// MARK: - Publishers
var slideSizePublisher = CurrentValueSubject<CGSize, Never>(.zero)
// MARK: - Observable interface
@Published var slideSize: CGSize = .zero
@Published var isInitialized: Bool = false
@Published var keyboardRect: CGRect = .zero {
didSet {
updateSlideSize()
}
}
//private var isKeyboardHidden: Bool = true
private var keyboardWillShow : Cancellable? = nil
private var keyboardWillHide : Cancellable? = nil
init() {
print("Keyboard Avoider init")
self.keyboardWillShow = NotificationCenter.default
.publisher(for: UIResponder.keyboardWillShowNotification)
.map { (notification) -> CGRect in
self.isInitialized = true
if let rect = notification.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? CGRect {
return rect
} else {
return .zero
}
}
.receive(on: RunLoop.main)
.assign(to: \.keyboardRect, on: self)
self.keyboardWillHide = NotificationCenter.default
.publisher(for: UIResponder.keyboardWillHideNotification)
.map {_ -> CGRect in .zero }
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
.assign(to: \.keyboardRect, on: self)
}
deinit {
print("Keyboard Avoider deinit")
self.keyboardWillShow?.cancel()
self.keyboardWillHide?.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment