У меня есть ViewController с TableView и textView. Я использую следующий код, так что когда клавиатура появляется, она поднимает textView и Tableview вверх.
bindToKeyboard
extension UIView {
func bindToKeyboard(){
NotificationCenter.default.addObserver(self, selector:
#selector(UIView.keyboardWillChange(_:)), name:
UIResponder.keyboardWillChangeFrameNotification, object: nil)
}
@objc func keyboardWillChange(_ notification: NSNotification) {
let duration = notification.userInfo!
[UIResponder.keyboardAnimationDurationUserInfoKey] as! Double
let curve = notification.userInfo![UIResponder.keyboardAnimationCurveUserInfoKey]
as! UInt
let curFrame = (notification.userInfo![UIResponder.keyboardFrameBeginUserInfoKey]
as! NSValue).cgRectValue
let targetFrame = (notification.userInfo![UIResponder.keyboardFrameEndUserInfoKey]
as! NSValue).cgRectValue
let deltaY = targetFrame.origin.y - curFrame.origin.y
UIView.animateKeyframes(withDuration: duration, delay: 0.0, options:
UIView.KeyframeAnimationOptions(rawValue: curve), animations: {
self.frame.origin.y += deltaY
},completion: {(true) in
self.layoutIfNeeded()
})
}
}
У меня проблема с верхними ячейками в tableView, я не могу прокрутить вниз, чтобы отобразить их, пока я не закрою клавиатура. Я искал возможные примеры кода, чтобы исправить это, но я не могу найти правильное решение. Любой вклад с благодарностью.
![keyboard is hiden](https://i.stack.imgur.com/shHEp.png)
![keyboard is shown](https://i.stack.imgur.com/YftAB.png)
РЕШЕНИЕ
Добавлено наблюдатель для viewDidLoad
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillHideNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(adjustForKeyboard), name: UIResponder.keyboardWillChangeFrameNotification, object: nil)
это было добавлено к классу
@objc func adjustForKeyboard(notification: Notification) {
guard let keyboardValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue else { return }
let keyboardScreenEndFrame = keyboardValue.cgRectValue
let keyboardViewEndFrame = view.convert(keyboardScreenEndFrame, from: view.window)
if notification.name == UIResponder.keyboardWillHideNotification {
tableView.contentInset = .zero
} else {
//Modify the top insets to 350 and the height of the keyboard > 10 ? 10 : 10
//to eliminate the gap between the bottom cell and the textView
tableView.contentInset = UIEdgeInsets(top: 350, left: 0, bottom: keyboardViewEndFrame
.height > 10 ? 10 : 10, right: 0)
}
tableView.scrollIndicatorInsets = tableView.contentInset
}
надеюсь, это кому-нибудь поможет.