首页 > 解决方案 > 当键盘显示一个文本视图但没有另一个文本视图时如何移动视图

问题描述

我在顶部有一个 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 不会向上移动视图?

标签: iosswiftxcodeuiviewuitextview

解决方案


在回答您的问题之前,根据您的代码,每次用户单击 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
         }
     }
}

推荐阅读