UICollectionView 项目间距不是常量

UICollectionView items spacing is not constant

我正在尝试显示一个 collection 视图,每个单元格在边框内显示一个字符串。我已将方向设置为 VERTICAL。因此,每行中可以有多个具有动态大小的单元格。但是单元格正在显示不同的内部项目space。

Collection 视图的当前状态:

我的collection视图配置如下:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    if(collectionView == tagsCollectionView)
    {
        if(self.propertyTypes.count > 0)
        {
            if(indexPath.row == 0)
            {
                return CGSize(width: "You searched for properties in: ".width(withConstrainedHeight: 25, font: UIFont(name: "Avenir-Book", size: 13)!), height: 30)
            }
            return CGSize(width: self.propertyTypes[indexPath.row - 1].width(withConstrainedHeight: 25, font: UIFont(name: "Avenir-Book", size: 13)!), height: 30)
        }
        return CGSize(width: 0, height: 0)
    }
    return "String".size(withAttributes: nil)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return 10
}

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

但是,collection 视图在水平方向时工作得非常好。

您可以使用 pod:https://github.com/mischa-hildebrand/AlignedCollectionViewFlowLayout 来实现您的功能。

你可以用这个库实现左、右、对齐等。

像这样使用它:

let alignedFlowLayout = collectionView?.collectionViewLayout as? AlignedCollectionViewFlowLayout
alignedFlowLayout?.horizontalAlignment = .left
alignedFlowLayout?.verticalAlignment = .top

查看图书馆以获取更多详细信息。