collectionView 中的约束

Constraints in collectionView

我想在我的 collectionView 单元格中有动态宽度和高度,所以我在每个屏幕上只有 2 个单元格。距离顶部、左侧、右侧和它们之间各 10px。

示例:

如果我有 320 像素的宽度(屏幕),我希望每个单元格有 145 像素,所以它会是 左起 10px +145(cell) + 10px between + 145(2nd cell) + 10px from right.

您可以使用堆栈视图,也可以设置单元格的宽度约束并将其拖到代码中以将常量设置为屏幕尺寸的一半。

还有为什么在以下情况下直接对单元格使用约束:

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

使用下面的代码:

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { 让宽度 = (screenSize.width - 30) / 2 let height = width * aspectRatio // aspectRatio - someValue 或将高度作为常量 return CGSizeMake(宽度, 高度) }

这对我来说效果很好..

使您的控制器符合 UICollectionViewDelegateFlowLayout 协议并实施方法:

import UIKit

class ViewController: UIViewController
{
    let numberOfCells = 9
    let kCellHeight : CGFloat = 100
    let kLineSpacing : CGFloat = 10
    let kInset : CGFloat = 10

    @IBOutlet weak var collectionView: UICollectionView!

    override func viewDidLoad()
    {
        super.viewDidLoad()
    }
}

extension ViewController : UICollectionViewDataSource
{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int
    {
        return numberOfCells
    }

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

extension ViewController : UICollectionViewDelegateFlowLayout
{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize
    {
        return CGSize(width: (UIScreen.main.bounds.width - 2*kInset - kLineSpacing)/2, height: kCellHeight)
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat
    {
        return kLineSpacing
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets
    {
        return UIEdgeInsets(top: kInset, left: kInset, bottom: kInset, right: kInset)
    }
}

附上截图: