Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: cleanup kvo #146

Merged
merged 2 commits into from
Apr 18, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions ios/KeyboardMovementObserver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@ public class KeyboardMovementObserver: NSObject {
private var prevKeyboardPosition = 0.0
private var displayLink: CADisplayLink?
private var keyboardHeight: CGFloat = 0.0
private var hasKVObserver = false

@objc public init(
handler: @escaping (NSString, NSNumber, NSNumber) -> Void,
Expand Down Expand Up @@ -82,18 +83,40 @@ public class KeyboardMovementObserver: NSObject {
name: UIWindow.didBecomeVisibleNotification,
object: nil
)
NotificationCenter.default.addObserver(
self,
selector: #selector(windowDidBecomeHidden),
name: UIWindow.didBecomeHiddenNotification,
object: nil
)
}

@objc func windowDidBecomeHidden(_: Notification) {
removeKVObserver()
}

@objc func windowDidBecomeVisible(_: Notification) {
let keyboardView = findKeyboardView()
setupKVObserver()
}

if keyboardView == _keyboardView {
private func setupKVObserver() {
if hasKVObserver {
return
}

_keyboardView = keyboardView
if keyboardView != nil {
hasKVObserver = true
keyboardView?.addObserver(self, forKeyPath: "center", options: .new, context: nil)
}
}

private func removeKVObserver() {
if !hasKVObserver {
return
}

keyboardView?.addObserver(self, forKeyPath: "center", options: .new, context: nil)
hasKVObserver = false
keyboardView?.removeObserver(self, forKeyPath: "center", context: nil)
}

// swiftlint:disable:next block_based_kvo
Expand Down