首页 > 解决方案 > CollectionView 单元格从内部自动布局调整大小

问题描述

我正在向单元格添加阴影,但是当我开始使用自动布局在单元格内设置对象时,它会对单元格的形状产生负面影响。我已经尝试了视图/笔尖加载的各个阶段,但似乎无法正确组合。我可以做些什么来允许在单元格内使用自动布局?

期望(无自动布局):

在此处输入图像描述

结果(将标签设置为“等宽”和与底部的距离后):

在此处输入图像描述

从视图控制器:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
      let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PlacesCell", for: indexPath) as! PlacesCollectionViewCell

    let shadowPath2 = UIBezierPath(rect: cell.bounds)
    cell.layer.cornerRadius = 10
    cell.layer.masksToBounds = false
    cell.layer.shadowColor = UIColor.black.cgColor
    cell.layer.shadowOffset = CGSize(width: CGFloat(2.0), height: CGFloat(6.0))
    cell.layer.shadowOpacity = 0.3
    cell.layer.shadowPath = shadowPath2.cgPath

    cell.name.text = someObjects[indexPath.row].name

    return cell
}

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

    let noOfCellsInRow = 2
    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
    let totalSpace = flowLayout.sectionInset.left
        + flowLayout.sectionInset.right
        + (flowLayout.minimumInteritemSpacing * CGFloat(noOfCellsInRow - 1))
    let size = Int((collectionView.bounds.width - totalSpace) / CGFloat(noOfCellsInRow))
    return CGSize(width: size, height: size)
}

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

     if let cell = sender as? UICollectionViewCell,
        let indexPath = self.placesCollectionView.indexPath(for: cell) {
        let vc = segue.destination as! PeopleViewController
        vc.placeForReference = someObjects[indexPath.row] //Pass object
    }
}

单元格的类仅继承自 UICollectionViewCell。

标签: swiftuicollectionviewautolayout

解决方案


弄清楚了; 在集合视图的设置中,我需要将“估计大小”更改为“无”。

在此处输入图像描述


推荐阅读