如何显示和隐藏带有子视图的键盘

时间:2019-03-01 17:29:27

标签: swift keyboard uitextfield subview uiwindow

我有一个自定义UIView,它是UIViewController的子视图。

我已将其添加到情节提要中,并将其设置为“隐藏”。

我的子视图也位于另一个我最初用作“模糊视图”的UIView中。

我具有取消隐藏和隐藏子视图的功能。

我的自定义子视图有一个UITextField。我可以显示键盘并毫无问题地向上移动子视图。当我输入或关闭键盘时,我的子视图会向上和向左移动。当我尝试再次显示子视图时,它显示不正确(从上到左)。

自定义子视图从屏幕中心开始。

目标是在显示键盘时将其上移,以使其不会覆盖子视图或UITextField,允许用户键入UITextField,然后关闭键盘并移动自定义子视图返回中心。

在我的UIViewController中:

// Showing the custom sub view
func displayCustomSubView() {
    if let window = UIApplication.shared.keyWindow {
        self.blurView.isHidden = false
        self.customSubView.isHidden = false
        self.blurView.frame = window.frame
        self.customSubView.center = window.center
        window.addSubview(self.blurView)
        UIApplication.shared.keyWindow?.bringSubviewToFront(self.blurView)
    }
}


// Hiding the custom sub view
// the custom sub view has a button I tap to hide
@objc func dismissCustomSubView() {
    self.blurView.isHidden = true
    self.customSubView.isHidden = true
}

// Show Keyboard
// Since I am using the window to make sure my blur view expands to the full frame, I have tried just moving the window up
@objc func keyboardWillShow(sender: NSNotification) {
    if let window = UIApplication.shared.keyWindow {
        window.frame.origin.y = -75
    }
}

// Hide Keyboard
@objc func keyboardWillHide(sender: NSNotification) {
    if let window = UIApplication.shared.keyWindow {
        window.frame.origin.y = 0
    }
}


// Custom Subview Extension

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

在上面添加了“自定义子视图扩展”。

1 个答案:

答案 0 :(得分:0)

首先在您的viewDidLoad()中添加此通知。并创建一个名为 timestamp() -> ErlangSystemTime = erlang:system_time(microsecond), MegaSecs = ErlangSystemTime div 1000000000000, Secs = ErlangSystemTime div 1000000 - MegaSecs*1000000, MicroSecs = ErlangSystemTime rem 1000000, {MegaSecs, Secs, MicroSecs} 的全局变量:

var keyboardH: CGFloat = 0

下面的功能:

  NotificationCenter.default.addObserver(
    self,
    selector: #selector(keyboardWillShow),
    name: UIResponder.keyboardWillShowNotification,
    object: nil
)

每次存在键盘时都会调用此函数,它将显示键盘高度,稍后我们可以使用此变量。

所以在您的代码中:

@objc func keyboardWillShow(_ notification: Notification) {
if let keyboardFrame: NSValue = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue {
    let keyboardRectangle = keyboardFrame.cgRectValue
    let keyboardHeight = keyboardRectangle.height
    self.keyboardH = keyboardHeight
}
相关问题