键盘出现时向上移动文本字段留下黑条

时间:2018-04-23 04:06:51

标签: ios swift keyboard

所以当你点击一个文本字段时它会工作,它会根据键盘的大小向上移动它。这太棒了,但是当我点击时,原始画面的底部不会跟着键盘向下移动。

我的意思是,只有当键盘完成消失时,视图框会在0处返回原来的y。我在下面有一些照片,在第二张照片中,你可以看到键盘向下移动,如丑陋的黑条仍然存在。

有谁知道为什么会这样?

以下是我要做的动画:

@objc func keyboardWillChange(notification: Notification)
{
    guard let keyboardRect = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue else {
        return
    }

    if notification.name == Notification.Name.UIKeyboardWillShow || notification.name == Notification.Name.UIKeyboardWillChangeFrame
    {
        view.frame.origin.y = -keyboardRect.height
    } else {
        view.frame.origin.y = 0
    }
}

deinit {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardDidHide, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
}

在viewDidLoad()内部

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardDidHide, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(notification:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)

https://i.imgur.com/P4hIMIW.jpg

https://i.imgur.com/40hXKHk.jpg

编辑:我只是想澄清视图框架确实返回其原始状态,它只是没有动画,也没有与键盘向下移动同步。它在键盘向下移动后执行,并在没有动画的情况下立即返回y = 0。当我单击文本字段时,它会在键盘向上移动时以精美的方式为其设置动画。

2 个答案:

答案 0 :(得分:0)

在AppDelegate中设置窗口背景颜色

window?.backgroundColor = .white

答案 1 :(得分:0)

<强> 1。在viewDidLoad()

中注册键盘隐藏和显示通知
 NotificationCenter.default.addObserver(self, selector: 
 #selector(keyBoardWillShow(notification:)), name: 
 .UIKeyboardWillShow , object: nil)

NotificationCenter.default.addObserver(self, selector: 
#selector(keyBoardWillHide(notification:)), name: .UIKeyboardWillHide 
, object: nil)

<强> 2。键盘隐藏和显示时调用

@objc func keyBoardWillShow(notification: NSNotification){
    adjustInsetForKeyBoards(show: true, notification: notification)
}

@objc func keyBoardWillHide(notification: NSNotification){
    adjustInsetForKeyBoards(show: false, notification: notification)
}

第3。您使用动画显示和隐藏键盘的逻辑

func adjustInsetForKeyBoards(show: Bool, notification: NSNotification){
  let userInfo = notification.userInfo ?? [:]

  let keyboardFrame = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
  let adjustment = (keyboardFrame.height * (show ? 1 : -1)) + 20
            self.yourView.contentInset.bottom += adjustment
}