在iPhone X上键盘视图中视图不断下移 [英] View keeps moving down in iPhoneX on keyboard dimissal

查看:184
本文介绍了在iPhone X上键盘视图中视图不断下移的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在不同的设备上进行测试,当我在iPhone X上进行测试时发现一个问题.

I'm carrying out tests on different devices and have noticed a problem when I come to test on an iPhone X.

基本上,在我看来,我有一个图像,一个文本字段和一个按钮;所有这些都在水平和垂直居中的堆栈视图中.当我点击文本字段并且键盘显示出来时,我将视图向上移动以免键盘阻塞任何内容,反之亦然.这是我的代码:

Basically, on my view, I have an image, a text-field and a button; all within a stack view that is centred horizontally and vertically. When I tap the text-field and the keyboard presents itself, I move the view upwards so as not to block any content with the keyboard - and vice-versa when the keyboard returns. Here is my code:

@objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y == 0{
            self.view.frame.origin.y -= keyboardSize.height/2
        }
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        if self.view.frame.origin.y != 0{
            self.view.frame.origin.y += keyboardSize.height/2
        }
    }
}

我已将观察者添加到viewDidLoad():

I have added the observers to viewDidLoad():

NotificationCenter.default.addObserver(self, selector: #selector(nameVC.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(nameVC.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)

这在模拟器中的所有设备类型上均能正常工作-除了iPhone X.

This has worked fine on all device types within the simulator - except for the iPhone X.

如下图所示,在iPhone X上关闭键盘后,视图向下移动.这会反复发生,直到键盘覆盖了文本字段,并且我必须重新启动应用程序才能重新获得控制权.

As shown by the image below, when the keyboard dismisses on an iPhone X, the view moves downwards. This happens again and again until the text-field is covered by the keyboard and I have to restart the app to regain control.

我对此感到完全困惑,该代码如何在除iPhone X之外的所有设备类型上工作?

I am completely stumped with this one, how can this code work on every device type except the iPhone X?

请任何人帮助

推荐答案

您应该使用keyboardFrameEndUserInfoKey而不是keyboardFrameBeginUserInfoKey,它会通过 safeAreaInsets 返回正确的高度.

You should use keyboardFrameEndUserInfoKey instead of keyboardFrameBeginUserInfoKey which returns the proper height with safeAreaInsets.

这篇关于在iPhone X上键盘视图中视图不断下移的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆