每行适合2个收集视图单元格(在所有设备上相同)

时间:2019-02-04 13:20:13

标签: swift uicollectionview autolayout

我创建了一个集合视图控制器,并尝试在两列中每行容纳2个单元格。我以我希望它在iphone 8上运行的方式获得它,但在其他设备(plus,5s,Xs max ...)上,一切都搞砸了。这是在iPhone 8上的图片:!https://imageshack.com/a/img923/3521/DFwwvc.png

在这里如何设置我的收藏夹视图:

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)
}}

1 个答案:

答案 0 :(得分:0)

您可以指定单元格的宽度和高度,使其在sizeForItemAtUICollectionViewDelegateFlowLayout的每部电话上成比例显示

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个单元格。