【问题标题】:CollectionView Cell Resizing from Internal AutoLayoutCollectionView 单元格从内部自动布局调整大小
【发布时间】:2020-03-27 19:35:48
【问题描述】:

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

期望(无自动布局):

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

从视图控制器:

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。

【问题讨论】:

  • 首先,您是否检查过 sizeForItem 是否被调用?如果是这样,请尝试使用标签的内容拥抱优先级。将其设置为较低的值,看看会发生什么。
  • sizeForItem 被调用,内容拥抱似乎没有太大影响。奇怪的是,它只发生在 UILabel 上,并且只发生在这个 ViewController 上。它是从另一个 VC 中的 segue 创建的这一事实是否重要?
  • 我更新了代码以添加segue。
  • segue 不应影响与您的问题相关的任何内容。我不知道您是否有其他选择,除了放弃等宽约束并将标签放在中心(如果这是您想要实现的目标)
  • 感谢您的回复。我真的希望能够在单元格中的图像上覆盖半透明的“下三分之一”;不知道如何在不告诉标签全宽的情况下做到这一点......

标签: swift uicollectionview autolayout


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-20
    • 2013-10-26
    • 1970-01-01
    • 1970-01-01
    • 2018-12-15
    相关资源
    最近更新 更多