ios – 键盘在UICollectionViewController中打破布局

前端之家收集整理的这篇文章主要介绍了ios – 键盘在UICollectionViewController中打破布局前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个水平的UICollectionViewController,其中每个单元格在单元格的底部包含一个UITextView.当我在UITextView内部点击时,键盘出现时,CollectionView的高度减少了260点(我注意到键盘的高度),然后增加130点,所以最终高度比预期的低130点.

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

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

UIViewController(只需启动CollectionViewController):

  1. class ViewController: UIViewController {
  2. override func viewDidAppear(_ animated: Bool) {
  3. super.viewDidAppear(animated)
  4.  
  5. let layout = UICollectionViewFlowLayout()
  6. layout.itemSize = view.bounds.size
  7. layout.scrollDirection = .horizontal
  8. layout.minimumLineSpacing = 0
  9. let fsPicVC = CollectionViewController(collectionViewLayout: layout)
  10. self.present(fsPicVC,animated: true) { }
  11. }
  12. }

CollectionViewController:

  1. class CollectionViewController: UICollectionViewController {
  2. override func viewDidLoad() {
  3. super.viewDidLoad()
  4.  
  5. self.collectionView!.register(CollectionViewCell.self,forCellWithReuseIdentifier: "Cell")
  6. }
  7.  
  8. override func collectionView(_ collectionView: UICollectionView,cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  9. let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell",for: indexPath)
  10.  
  11. return cell
  12. }
  13. }

非常感谢

解决方法

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

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

1)在ViewController中替换这些行:

  1. let fsPicVC = CollectionViewController(collectionViewLayout: layout)
  2. self.present(fsPicVC,animated: true) { }

  1. let collectionView = UICollectionView(frame: view.bounds,collectionViewLayout: layout)
  2. collectionView.register(CollectionViewCell.self,forCellWithReuseIdentifier: "Cell")
  3. collectionView.dataSource = self
  4. view.addSubview(collectionView)

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

  1. extension ViewController: UICollectionViewDataSource {
  2.  
  3. func numberOfSections(in collectionView: UICollectionView) -> Int {
  4. return 1
  5. }
  6.  
  7. func collectionView(_ collectionView: UICollectionView,numberOfItemsInSection section: Int) -> Int {
  8. return 10
  9. }
  10.  
  11. func collectionView(_ collectionView: UICollectionView,for: indexPath)
  12.  
  13. // Configure the cell
  14.  
  15. return cell
  16. }
  17. }

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

PS你也可能想要1)扩展ViewController以符合UICollectionViewDelegateFlowLayout和2)使collectionView全局.

猜你在找的iOS相关文章