仅在小型设备上出现键盘时如何移动视图

时间:2019-10-07 09:09:05

标签: swift xcode keyboard

我正在使用iPhone应用程序,并且有多个UITextFields用于输入。

仅适用于iPhone 5、6之类的小型设备的问题。出现键盘时,底部的textFields隐藏。 与XR,XS Max这样的大iPhone屏幕配合使用都很好

如何添加条件以检查底部的文本字段是否隐藏?

 guard let keyboardReact = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
            return
        }
        let screen = view.frame.size.height - keyboardReact.height
        let safeAreHeight = self.view.frame.height - self.topLayoutGuide.length - self.bottomLayoutGuide.length

        if  safeAreHeight + keyboardReact.height > view.frame.size.height {
            if currentTappedTextField == phoneTextField || currentTappedTextField == employeeEmailTextField  || currentTappedTextField == relationTextField {
                if notification.name == UIResponder.keyboardWillShowNotification || notification.name == UIResponder.keyboardWillChangeFrameNotification{
                    view.frame.origin.y = -(keyboardReact.height)
                } else {
                    view.frame.origin.y = 0
                }
            }
        }

这适用于所有屏幕尺寸,我希望它仅在键盘上隐藏textFields时起作用

1 个答案:

答案 0 :(得分:0)

现在您可以计算键盘高度并以编码方式移动视图

func liftViewUp(notification: NSNotification){
        if let keyboardSize = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? CGRect {
       // manage your view accordingly here



 if currentTappedTextField == phoneTextField || currentTappedTextField == employeeEmailTextField  || currentTappedTextField == relationTextField {
                    if notification.name == UIResponder.keyboardWillShowNotification || notification.name == UIResponder.keyboardWillChangeFrameNotification{



     let textFieldPosition = currentTappedTextField.frame.origin.y + currentTappedTextField.frame.size.height

// check if textfield will hide behind keyboard
  if textFieldPosition > (view.frame.size.height - keyboardReact.height){

            view.frame.origin.y = -(keyboardReact.height)
     }else {
            view.frame.origin.y = 0
           }
 } else {
          view.frame.origin.y = 0
         }
      }
 }
}

或者您可以尝试使用此第三方库IQKeyboardManager

您可能会得到答案here