iPhone X 中出现键盘时向上移动屏幕 [英] Move screen up when keyboard appears in iPhone X

查看:40
本文介绍了iPhone X 中出现键盘时向上移动屏幕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的代码在键盘显示和隐藏时上下移动屏幕

I use code below to move screen up and down when keyboard show and hide

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

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

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

它适用于除 iPhone x 之外的所有设备(我认为问题是 iPhone X 底部浪费了空间)

It works in all devices except iPhone x (I think the problem is iPhone X bottom wasted space)

问题是键盘大小在显示之前和之后发生变化,导致视图向下和向下......

Problem is that keyboard size change before shown and after that and cause the view go down and down and down...

有人可以帮忙吗?

推荐答案

你还应该考虑安全区域插入

You should also consider safe area insets

let endFrame = (userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? CGRect.zero
let bottomSpace = keyboardValues.endFrame.maxY - keyboardValues.endFrame.minY - self.view.safeAreaInsets.bottom

而且你不应该添加.这些通知可能会发布多次.使用绝对值.

And you should not be additive. These notifications may be posted multiple times. Use absolute values.

这篇关于iPhone X 中出现键盘时向上移动屏幕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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