为集合视图单元格设置自动布局宽度和高度约束的最佳做法?

Ale*_*x P 8 ios autolayout uicollectionview uicollectionviewcell swift

我正在设计一个快速构建的ios 8应用程序的UI.我对autolayout和约束有中级知识.这是我的情况:我有一个自定义集合视图控制器和集合视图单元格.我想在界面构建器中使用"等宽"和"相等高度"约束来设置单元格的宽度和高度相对于父视图的乘数 - 而不是使用固有的高度/宽度属性,如320 x 94.

这是我尝试过的

  1. 使用IB内部大小类的固有宽度和高度.(这不起作用)
  2. 控制 - 从UICollectionViewCell拖动到CollectionView(看不到"相等高度"和"相等宽度"甚至不是约束选项)

我应该只考虑内在的高度和宽度,并假设CollectionViewFlowLayout将照顾我或有没有办法以编程方式执行此操作?

谢谢.亚历克斯

War*_*ton 0

使用这些UICollectionViewDelegateFlowLayout方法来调整单元格大小

例如,如果您希望在视图宽度上有 3 个单元格

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize
{
    let width = CGRectGetWidth(collectionView.bounds)
    let hcount = 3
    let gapcount = CGFloat(hcount) + 1
    //this should be a class var/constant which you can feed into the minimumLineSpacingForSectionAtIndex delegate
    let gap = 10 
    let kwidth = width - gap
    let keywidth = kwidth/CGFloat(hcount)

    return CGSize(width:keywidth,height:50)
}
Run Code Online (Sandbox Code Playgroud)

您可以使用以下命令调整单元格之间的距离

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat

和边缘插入

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets