键盘看到时Scrollview隐藏文本字段

时间:2017-01-18 10:10:44

标签: ios swift3

我使用的是swift 3,我有12个textfield的形式。一旦用户进入scrollview底部的textfield,键盘隐藏了textfield.So为了解决这个问题,我在下面添加了这段代码。然而,下面添加代码的问题是,当我隐藏键盘时,无法向上或向下滚动。滚动视图中的滚动会以某种方式被禁用。

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    registerKeyboardNotifications()
}   

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    unregisterKeyboardNotifications()
}   

func registerKeyboardNotifications() {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(self.keyboardDidShow(notification:)),
                                           name: NSNotification.Name.UIKeyboardDidShow,
                                           object: nil)
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(self.keyboardWillHide(notification:)),
                                           name: NSNotification.Name.UIKeyboardWillHide,
                                           object: nil)
}    

func unregisterKeyboardNotifications() {
    NotificationCenter.default.removeObserver(self)
}  

func keyboardDidShow(notification: NSNotification) {      
    print("keyboard seen")
    let userInfo: NSDictionary = notification.userInfo! as NSDictionary
    let keyboardInfo = userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue
    let keyboardSize = keyboardInfo.cgRectValue.size
    let contentInsets = UIEdgeInsets(top: 0, left: 0, bottom: keyboardSize.height, right: 0)
    scrollView.contentInset = contentInsets
    scrollView.scrollIndicatorInsets = contentInsets
}    

func keyboardWillHide(notification: NSNotification) {
    print("keyboard hidden")
    scrollView.contentInset = UIEdgeInsets.zero
    scrollView.scrollIndicatorInsets = UIEdgeInsets.zero
}

0 个答案:

没有答案