如何在所有设备中使用 swift4 在 CollectionView 中显示三列

How to show three columns in a CollectionView using swift4 in all devices

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
    
    if collectionView == self.collectionViewVideo {

        var collectionViewSize = collectionViewVideo.frame.size
        collectionViewSize.width = collectionViewSize.width/3.0 //Display Three elements in a row.
        return collectionViewSize
    } else {
        return CGSize(width: 60, height: 60)
    }
    
    
}

您还需要考虑 space。 Space 是您的 collection 查看项目 space

以下代码有两个单元格和 20 spaces。 (我不是在写你需要的代码你应该自己做)

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

    //--------------------------------------------------------------------------------

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

    //--------------------------------------------------------------------------------

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

    //--------------------------------------------------------------------------------

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
       return UIEdgeInsetsMake(0, 20, 20, 20)
    }
}

这里60表示SPACE20CELLSPACE20CELLSPACE20