【问题标题】:View didn't up by keyboard on second click into text field第二次点击文本字段时,键盘没有显示视图
【发布时间】:2018-07-01 22:37:20
【问题描述】:

我有一个带有登录屏幕(手机和密码)的 iOS 应用。让我们想象一个案例:

  1. 用户点击电话号码文本字段和数字键盘出现,视图是键盘。
  2. 用户填写电话号码并点击密码文本字段,键盘从数字布局更改为标准。
  3. 用户点击键盘上的返回按钮,键盘关闭,视图关闭。
  4. 用户点击电话号码文本字段或密码以更多时间进行数据更正

在第 4 阶段,键盘出现,但视图不再显示,当我点击键盘上的返回按钮时,视图甚至下降,屏幕顶部出现黑线。我该如何解决这个问题?在代码中我有这个:

func textFieldShouldReturn(_ textField: UITextField) -> Bool {
    textField.resignFirstResponder()
    return true
}

在 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)

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

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

【问题讨论】:

    标签: ios swift ios11 swift4


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

      我建议你使用 IQKeyboardmanager。它会自动处理这些事情 GitHub链接-IQKeyboardManger

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-09
        • 1970-01-01
        • 1970-01-01
        • 2017-08-14
        • 2018-01-06
        • 2012-10-22
        • 2020-10-27
        相关资源
        最近更新 更多