Skip to content

Instantly share code, notes, and snippets.

@Abhishek9634
Created March 31, 2019 03:06
Show Gist options
  • Save Abhishek9634/2837da3b65aaaf94a9becc117ecb3e75 to your computer and use it in GitHub Desktop.
Save Abhishek9634/2837da3b65aaaf94a9becc117ecb3e75 to your computer and use it in GitHub Desktop.
class MYViewController: UIViewController {
......
.....
...
private var currentOffset: CGPoint = .zero
private lazy var inputFields: [UIView] = {
return [self.customerField, self.materialField,
self.startTimeTextField, self.endTimeTextField,
self.notesTextView]
}()
...
....
}
extension MYViewController {
private func setupKeyboardNotifications() {
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillShow(_:)),
name: NSNotification.Name.UIKeyboardWillShow,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(keyboardWillHide(_:)),
name: NSNotification.Name.UIKeyboardWillHide,
object: nil)
}
@objc
private func keyboardWillShow(_ sender: Notification) {
self.currentOffset = self.tableView.contentOffset
guard let inputView = self.inputFields.filter({
$0.isFirstResponder
}).first else { return }
let point = inputView.convert(inputView.bounds.origin,
to: self.view)
let x = self.tableView.contentOffset.x
let y = point.y - 50
self.tableView.setContentOffset(CGPoint(x: x, y: y),
animated: true)
}
@objc
private func keyboardWillHide(_ sender: Notification) {
self.tableView.setContentOffset(self.currentOffset,
animated: true)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment