每行安装 2 collection 个视图单元格(在所有设备上都相同)

Fitting 2 collection view cell per row (same on all devices)

我创建了一个 collection 视图控制器,我正在尝试在两列中每行放置 2 个单元格。我在 iphone 8 上按照我想要的方式得到它 运行,但在其他设备(加上 5s,Xs max ...)上它变得一团糟。这是 iphone 8:!https://imageshack.com/a/img923/3521/DFwwvc.png

上的照片

下面是我的 collection 视图的设置方式:

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

    collectionView.backgroundColor = .clear
    collectionView.contentInset = UIEdgeInsets(top: 10.0,
                                               left: 2.0,
                                               bottom: 10.0,
                                               right: 2.0)

    return nomeItem.count
}//func numberOfItemsInSection
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let celula = collectionView.dequeueReusableCell(withReuseIdentifier: "PronafCollectionCell", for: indexPath as IndexPath) as! PronafCollectionCell

    celula.labelNumeroItem.text = String(indexPath.row+1)
    celula.labelTitulo.text = nomeItem[indexPath.row]
    celula.labelDescricao.text = descricaoItem[indexPath.row]

    return celula
}//func cellForItemAt

func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {

    switch (indexPath.row){
    case 0:
        self.performSegue(withIdentifier: "segueDescricao", sender: self)
    case 1:
        self.performSegue(withIdentifier: "segueProponente", sender: self)
    case 2:
        self.performSegue(withIdentifier: "segueResponsavelTecnico", sender: self)
    case 3:
        self.performSegue(withIdentifier: "segueCar", sender: self)
    case 4:
        self.performSegue(withIdentifier: "segueImovel", sender: self)
    case 5:
        self.performSegue(withIdentifier: "segueDesenho", sender: self)
    case 6:
        self.performSegue(withIdentifier: "segueBuscar", sender: self)
    case 7:
        self.performSegue(withIdentifier: "segueResumo", sender: self)
    default:
        break
    }//switch (indexPath.row)
}}

您可以指定单元格的宽度和高度,使其在 sizeForItemAtUICollectionViewDelegateFlowLayout

的每个 phone 上成比例
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return CGSize(width: collectionView.frame.width / 2, height: /* your desired height here */)
}

提示:您甚至可以通过乘以这样的值使其小于屏幕的一半: (collectionView.frame.width / 2) * 0.98,也可以减去常数值

我建议在 调整单元格大小后设置 UIEdgeInsets

注意:每行的单元格数量是根据适合UICollectionView宽度的单元格数量计算的。因此,具有一半宽度的单元格将适合每行 2 个单元格。