【问题标题】:How to show and hide the keyboard with a subview如何使用子视图显示和隐藏键盘
【发布时间】:2019-07-23 18:43:03
【问题描述】:

我有一个自定义 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
    }
}

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

【问题讨论】:

  • 我们可以看到自定义子视图文本字段委托函数吗?

标签: swift keyboard uitextfield subview uiwindow


【解决方案1】:

首先在您的 viewDidLoad() 中添加此通知。并创建一个名为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
}

每次键盘出现时都会调用这个函数,它会显示键盘高度,以后我们可以使用这个变量。

所以在你的代码中:

@objc func keyboardWillShow(sender: NSNotification) {
if let window = UIApplication.shared.keyWindow {
    let position = window.frame.origin.y - keyboardH
    window.frame.origin.y = position
     }
}

【讨论】:

  • 我可以显示键盘没问题,它让我的子视图在关闭键盘后重新定位并在打字时保持屏幕不变。
猜你喜欢
  • 1970-01-01
  • 2014-03-08
  • 2012-04-20
  • 2015-03-14
  • 2015-06-21
  • 1970-01-01
  • 1970-01-01
  • 2013-02-14
  • 1970-01-01
相关资源
最近更新 更多