我有一个带有许多文本字段的滚动视图。当我向上滚动滚动视图以使键盘不会隐藏某些子视图时,我无法一直滚动到滚动视图的顶部。这是我的代码。有人可以帮忙吗?
class IncomingPackageViewController: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self,selector:#selector(self.keyboardWillShow),name:UIResponder.keyboardDidShowNotification, object: nil)
NotificationCenter.default.addObserver(self,selector: #selector(self.keyboardWillHide),name:UIResponder.keyboardDidHideNotification, object: nil)
}
@objc func keyboardWillShow(notification: Notification) {
guard let userInfo = notification.userInfo,
let frame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {return}
let contentInset = UIEdgeInsets(top: 0, left: 0, bottom: frame.height, right: 0)
if self.view.frame.origin.y == 0 {
self.view.frame.origin.y -= contentInset.bottom
}
}
@objc func keyboardWillHide(notification: Notification) {
if self.view.frame.origin.y != 0 {
self.view.frame.origin.y = 0
}
}
}
您应该使用scrollView.contentInset
,不要弄乱ViewControllers视图框架。
我还建议您使用tableView
,因为它免费提供了该功能。