简体   繁体   中英

My Scrollview doesn't scroll all the way up after pushing up the keyboard Swift iOS

I have a scrollview with lots of textfields inside it. When I push up my scroll view so that the keyboard does not hide some of the subviews, I can't scroll all the way up to the top of scrollview. Here is my code. Can anyone help?

uiscrollview 的约束

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
        }
    }
}

You should use the scrollView.contentInset , you shouldn't mess with the ViewControllers view frame.

I also recommend that you use a tableView since it gives you that behavior for free.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM