CollectionView 单元格自动调整大小

CollectionView Cell Auto resizing

我创建了一个 UICollectionView,其中有一个原型单元格。我想要每行 2 个单元格,运行 它在较小的屏幕上给我每行一个单元格。 在更大的屏幕上,单元格之间的距离会增加。我只是在谈论 iPhone。

我想我必须通过获取屏幕宽度并将其除以 2 以编程方式设置约束。我知道如何获取屏幕宽度并将其除以 2 但我不知道如何以编程方式为单元格提供宽度和高度.

UICollectionViewDelegateFlowLayout 为此定义了一个方法。

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
     // return a CGSize 
 }

示例:

class MyViewController : UIViewController, UICollectionViewDelegateFlowLayout {

    override func viewDidLoad() {
        super.viewDidLoad()

        self.collectionView.delegate = self
        self.collectionView.dataSource = self
    }

  // ...

    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        return CGSize(width: CGFloat(self.view.frame.size.width / 2), height: self.view.frame.size.height) 
    }

  // ...
}