Created
June 18, 2021 09:26
-
-
Save hira22/b825e9e4a1ea5d878a5ddbc12d29ef20 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
import Combine | |
import UIKit | |
class SampleViewController: UIViewController { | |
private var cancellables: Set<AnyCancellable> = [] | |
@IBOutlet private var sampleView: UIView! | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
NotificationCenter.default | |
.publisher(for: UIResponder.keyboardWillShowNotification) | |
.merge(with: NotificationCenter.default.publisher(for: UIResponder.keyboardWillChangeFrameNotification)) | |
.receive(on: DispatchQueue.main) | |
.sink { [weak self] in self?.animateKeyboard(notification: $0, keyBoardWillShow: true) } | |
.store(in: &self.cancellables) | |
NotificationCenter.default | |
.publisher(for: UIResponder.keyboardWillHideNotification) | |
.receive(on: DispatchQueue.main) | |
.sink { [weak self] in self?.animateKeyboard(notification: $0, keyBoardWillShow: false) } | |
.store(in: &self.cancellables) | |
} | |
private func animateKeyboard(notification: Notification, keyBoardWillShow: Bool) { | |
guard | |
let rect: CGRect = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect, | |
let duration: TimeInterval = notification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval | |
else { return } | |
UIView.animate(withDuration: duration, | |
animations: { | |
self.sampleView.transform = keyBoardWillShow ? CGAffineTransform(translationX: 0, y: -rect.size.height + 1) : .identity | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment