【发布时间】:2020-05-13 13:37:49
【问题描述】:
我有一个带有 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
}
希望这对任何人都有帮助。
【问题讨论】:
-
分享您的 UI 向上滚动时的外观
-
@Niraj_iOS 屏幕截图已添加。谢谢!
-
哥们,你需要把
UITableView&UITextView里面UIScrollView绑定tableview高度约束,并在键盘显示/隐藏时进行管理。希望这对您有所帮助。如果需要更多信息,请告诉我。 -
感谢您的评论。我能够在没有 UIScrollView 的情况下做到这一点。我用解决方案更新了我的帖子。
标签: ios swift xcode uitableview uiscrollview