【问题标题】:How to move the view when the keyboard presents with one textview but not another one当键盘显示一个文本视图但没有另一个文本视图时如何移动视图
【发布时间】:2020-07-29 05:17:58
【问题描述】:

我在顶部有一个 UITextView,在中间有一个 UITextView,在底部有一个 UITextView。 如果使用底部的 UITextView 或中心的 UITextView,我想在键盘出现时向上移动视图,但使用顶部的 UITextView 时视图不应该移动。

我该如何进行这项工作?

func showLoginKeyBoard()
{
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil)
}
@objc func keyboardWillShow(notification: NSNotification)
{
    if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue
    {
        if self.view.frame.origin.y == 0
        {
            self.view.frame.origin.y -= keyboardSize.height
        }
    }
}


func textViewDidBeginEditing(_ textView: UITextView)
{
    if textView == centreTextView
    {
        showLoginKeyBoard()
    }

    if textView == bottomTextView
    {
        showLoginKeyBoard()
    }
}

目前,当任何 UITextViews 成为FirstResponder 时,视图会向上移动,这意味着当使用顶部 UITextView 时,它是不可见的。

如何确保顶部的 UITextView 不会向上移动视图?

【问题讨论】:

    标签: ios swift xcode uiview uitextview


    【解决方案1】:

    在回答你的问题之前, 根据您的代码,每次用户单击 textView 您添加观察者。不要这样做。在 viewDidLoad() 中添加观察者,不要忘记在 viewDidDisappear() 中删除观察者。否则会导致内存泄漏。

    现在,回答问题

    定义文件私有可选文本视图

    var currentTextView:UITextView?
    

    然后在textViewDidBeginEditing

    中赋值textField
    func textViewDidBeginEditing(_ textView: UITextView){
       currentTextView = textView
    }
    

    现在可以根据currentTextView显示或不显示

    @objc func keyboardWillShow(notification: NSNotification){
         if let txtView = currentTextView{
             txtView != topTextView {
             //move up the view
             }
         }
    }
    

    【讨论】:

    • 我仍在尝试更改所有代码以使其正常工作,因为我在 UIViewController 扩展中同时使用了 showLoginKeyboard() 和 keyboardWillShow,因为有 3 个具有此设置的控制器以及顶部和底部控制器是自定义类。
    【解决方案2】:

    我建议使用 IQKeyboardManager 库,它只需一行代码即可处理所有键盘事件

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-16
      • 2017-10-20
      • 2012-11-08
      • 1970-01-01
      • 2017-04-28
      • 2011-08-23
      • 1970-01-01
      相关资源
      最近更新 更多