在选择文本字段时,调整键盘

时间:2016-11-01 19:35:03

标签: ios swift uiscrollview autolayout xib

我在xib中有一个ViewController(登录视图),它有2个UITextField和1个UIButton组件。视图层次结构是

 UIView
     -> UIScrollView
         -> UIView (contentView)
             -> UITextField
             -> UITextField
             -> UIButton

我在视图中使用autolayout。 UIScrollView有4个约束,即前导,尾随,顶部和顶部。底部与其超级视图对齐(UIViewController视图)。 ContentView有4个约束,即前导,尾随,顶部和顶部。底部到超级视图(UIScrollView)和宽度匹配UIViewController视图。

我已按照Apple documentation中的步骤向上或向下滚动,当用户选择UITextField时,键盘不在UITextField之上。

当显示键盘时,滚动视图会向上滚动,但是当键盘被隐藏时,scrollview不会向后滚动。任何帮助表示赞赏。

override func viewDidLoad() {
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

func keyboardWillHide(notification: NSNotification) {

        let contentInsets: UIEdgeInsets = UIEdgeInsets.zero
        self.scrollView.contentInset = contentInsets
        self.scrollView.scrollIndicatorInsets = contentInsets
    } 

func keyboardWillShow(notification: NSNotification) {

        if let activeField = self.activeField, let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {

            let contentInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize.height, right: 0.0)

            self.scrollView.contentInset = contentInsets
            self.scrollView.scrollIndicatorInsets = contentInsets

            var aRect = self.view.frame

            aRect.size.height -= keyboardSize.size.height
            if (!aRect.contains(activeField.frame.origin)) {
                self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
            }
        }
    }

2 个答案:

答案 0 :(得分:0)

答案 1 :(得分:0)

scrollView df.loc[ (df.Rand <= 0.4) , 'Park' ] = lambda:[5,10,15,20] df.loc[ (df.Rand > 0.4) & (df.Rand <= 0.8) , 'Park' ] = lambda:[4,9,14,19] df.loc[ (df.Rand > 0.8) , 'Park' ] = lambda:[6,11,16,21] df.Park = df.Park.apply(lambda x: x()) 不是contentInset.top因此我遇到了问题。在隐藏键盘后,将0.0正确更改后,将scrollView设置为原始位置。

contentInset.top