当键盘出现时 CollectionView 向上移动然后 returns 到上一个位置

CollectionView moves up when keyboard appears then returns to previous position

我的单元格中有一个 collectionView 和一个 textView。何时出现 textView 键盘但随后 collectionView 向上移动然后 return 到上一个位置。如何阻止它?如何在出现键盘时停止移动 collectionView?

这是我简单明了的代码:

 class MainReadAssistantViewController: UICollectionViewController, 
UICollectionViewDelegateFlowLayout {
let wordOrPhraseCellId = "wordOrPhraseCellId"

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
   collectionView?.backgroundColor = UIColor.blue
collectionView?.register(WordOrPhraseCell.self, forCellWithReuseIdentifier: wordOrPhraseCellId)

    collectionView?.register(SentenceOrASuperLongPhrase.self, forCellWithReuseIdentifier: sentenceOrASuperLongPhraseCellId)
    collectionView?.isScrollEnabled = false

   // collectionView?.alwaysBounceVertical = true
     }

override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return 1
}


func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {


    return CGSize(width: view.frame.width, height: view.frame.height - 150)
}

override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    var cell = collectionView.dequeueReusableCell(withReuseIdentifier: 
        return cell

        }
    }


    return cell
}

这是键盘出现后 uicollectionView 移动的例子。

这是为了防止键盘隐藏文本字段。如果您想停止该行为(我不建议)覆盖viewWillAppear(_:)而不调用super.viewWillAppear(animated)。像这样:

override func viewWillAppear(_ animated: Bool) {

}

请注意,重写 viewWillAppear(_:) 而不调用 super 方法可能会导致未定义的行为。