CollectionView的sizeForItemAtIndexPath从来没有被调用

这真让我抓狂! 我有一个UICollectionViewController,如下所示:

class PhrasesCompactCollectionViewController: UICollectionViewController 

numberOfSections和cellForItemAt被调用,但sizeForItemAtIndexPath永远不会被调用。 我在其他地方使用相同的确切代码,并且正确启动。 我正在使用Xcode 8 Beta 6。

 func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSize(width: 120, height:120) } 

您需要指定在类声明中实现协议UICollectionViewDelegateFlowLayout

class PhrasesCompactCollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout

Swift 3

要设置UICollectionView的单元大小,您需要创build并自定义UICollectionViewFlowLayout对象。 自定义属性并将该布局对象设置为UICollectionView对象。

根据您的要求(您想要的单元格高度和宽度)更改cellheight和cell cellWidth对象。

 override func viewDidLoad() { super.viewDidLoad() let cellWidth : CGFloat = myCollectionView.frame.size.width / 4.0 let cellheight : CGFloat = myCollectionView.frame.size.height - 2.0 let cellSize = CGSize(width: cellWidth , height:cellheight) let layout = UICollectionViewFlowLayout() layout.scrollDirection = .vertical //.horizontal layout.itemSize = cellSize layout.sectionInset = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) layout.minimumLineSpacing = 1.0 layout.minimumInteritemSpacing = 1.0 myCollectionView.setCollectionViewLayout(layout, animated: true) myCollectionView.reloadData() } 

请确保:如果您添加了sizeForItemAt indexPath方法,则必须删除方法…

删除下面的方法

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

Swift 3+中使用这种方法:

 func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize(width:(collectionView.frame.height-90)/2, height: 100) } 

确保你的课程符合两者

  • UICollectionViewDelegate

  • UICollectionViewDelegateFlowLayout

对我来说(在Swift 3.1中)方法必须像这样公开:

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

不要忘记公开