我有一个带有TableView和textView的ViewController。我使用下面的代码,以便当键盘出现时,它会向上推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中的顶部单元格,除非关闭键盘,否则无法向下滚动以显示它们。我一直在寻找可能的代码样本来解决这个问题,但我似乎找不到正确的解决方案。任何输入都非常感谢。
解决方案
将观察者添加到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
}
希望这对任何人都有帮助。
3条答案
按热度按时间toe950271#
您正在更改表视图的
frame
,但应修改contentOffset
或contentInsets
属性。如果移动框架,整个表格将移出屏幕,因此顶部的单元格也会移出屏幕。
有很多(我的意思是很多)教程可能会帮助你,见例如。https://www.hackingwithswift.com/example-code/uikit/how-to-adjust-a-uiscrollview-to-fit-the-keyboard
还可以在例如以下方面找到多个解决方案:github。
lmyy7pcs2#
这对我来说很好
在ViewDidLoad中添加以下内容:
实现此方法:
@objc func adjustForKeyboard(通知:通知){
f3temu5u3#
你也可以在你的项目中使用IQKeyboardManager cocoapod