CollectionView sizeForItemAtIndexPath never called

前端 未结 15 1281
一整个雨季
一整个雨季 2020-12-24 11:17

This is driving me crazy! I have a UICollectionViewController as shown below:

class PhrasesCompactCollectionViewController: UICollectionViewController


        
相关标签:
15条回答
  • 2020-12-24 11:43

    Just add: UICollectionViewDelegateFlowLayout

    class YourClass: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {}
    
    0 讨论(0)
  • 2020-12-24 11:46

    I had this issue last night. Finally solved it at midnight when I realised 'didSelectItemAtIndex' method was not closed off with a closure bracket "}"

    I added a closure bracket at the very bottom of the class when asked by the compile error. So in effect all the methods below 'didSelectItemAtIndex' were inside that method.

    Posting here just in case anyone else wastes 4 hours of their evenings on this one :-(

    0 讨论(0)
  • 2020-12-24 11:46

    If you're using autolayout, make sure collectionView.translatesAutoresizingMaskIntoConstraints = false is set.

    0 讨论(0)
  • 2020-12-24 11:47

    First class need confirm to UICollectionViewDelegateFlowLayout. Then you need to write following code in viewDidLoad():

    //To tell the UICollectionView to use your UIViewController's UICollectionViewDelegateFlowLayout methods

    collectionView.delegate = self
    

    // If you want to set your own collection view flow layout

    let layout = UICollectionViewFlowLayout()
    layout.scrollDirection = .vertical //depending upon direction of collection view
    
    self.collectionView?.setCollectionViewLayout(layout, animated: true)
    

    By using this code UICollectionViewDelegateFlowLayout method

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

    will get called, you can set size in this method.

    0 讨论(0)
  • 2020-12-24 11:51

    You need to specify that you implement the protocol UICollectionViewDelegateFlowLayout in your class declaration.

    class PhrasesCompactCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout

    0 讨论(0)
  • 2020-12-24 11:51

    Use this method

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

    Instead of

    private func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
    
    }
    
    0 讨论(0)
提交回复
热议问题