键盘在UICollectionViewController中打破布局

Ste*_*one 8 ios uicollectionview uicollectionviewlayout swift

我有一个水平的UICollectionViewController,其中每个单元格在单元格的底部包含一个UITextView.当我在UITextView内部点击时,键盘出现时,CollectionView的高度减少了260点(我注意到键盘的高度),然后增加130点,所以最终高度比预期的低130点.

你知道为什么框架会以这种方式改变吗?

我在下面列出了最相关的部分,或者你可以在这里找到测试项目:https://github.com/johntiror/testAutomaticPush/tree/master

UIViewController(只需启动CollectionViewController):

class ViewController: UIViewController {
  override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    let layout = UICollectionViewFlowLayout()
    layout.itemSize = view.bounds.size
    layout.scrollDirection = .horizontal
    layout.minimumLineSpacing = 0
    let fsPicVC = CollectionViewController(collectionViewLayout: layout)
    self.present(fsPicVC, animated: true) { }
  }
}
Run Code Online (Sandbox Code Playgroud)

CollectionViewController:

class CollectionViewController: UICollectionViewController {
  override func viewDidLoad() {
    super.viewDidLoad()

    self.collectionView!.register(CollectionViewCell.self, forCellWithReuseIdentifier: "Cell")                
  }

  override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)    

    return cell
  }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

非常感谢

mmd*_*080 3

首先,我必须给我两分钱,故事板很棒:)

对于此用例,您可能不想使用 CollectionViewController。如果您决定使用它,我还发布了另一个答案。这是将 CollectionView 移动到 ViewController 的最快方法。这解决了您的问题,但没有考虑自动布局。

1) 在 ViewController 中替换这些行:

let fsPicVC = CollectionViewController(collectionViewLayout: layout)
self.present(fsPicVC, animated: true) { }
Run Code Online (Sandbox Code Playgroud)

let collectionView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
collectionView.register(CollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
collectionView.dataSource = self
view.addSubview(collectionView)
Run Code Online (Sandbox Code Playgroud)

2)将其添加到 ViewController 的最底部(在ViewController 类之外):

extension ViewController: UICollectionViewDataSource {

  func numberOfSections(in collectionView: UICollectionView) -> Int {
    return 1
  }

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

  func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath)

    // Configure the cell

    return cell
  }
}
Run Code Online (Sandbox Code Playgroud)

最后,您可以删除 CollectionViewController,因为它现已被替换。

PS 您可能还想 1) 扩展 ViewController 以符合 UICollectionViewDelegateFlowLayout 和 2) 使 collectionView 全局化。