可扩展的UICollectionViewCell重新定位问题



我有一个带有可扩展uicollectionviewcell的uicollectionview。 在iPhone上,每行都有1列,没有问题。 但是在iPad上,行有2列,扩展单元格后出现问题。

这是单元格屏幕截图。 未展开

扩大

单击箭头按钮时,我正在重新加载项目

self.collectionView.reloadItems(at: [indexPath])

大小项函数

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = store.pickList[indexPath.row].expanded ? CGFloat(414) : CGFloat(168)
var width = CGFloat(0)
if Constants.isPad { width = (self.view.frame.size.width - 25 - 12 - 12) / 2 }
else { width = self.view.frame.size.width - 12 - 12 }
return CGSize(width: width, height: height)
}

CellforRowAt:

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

.....
if data.expanded {
UIView.animate(withDuration: 0.25, animations: {
cell.bottomView.frame = CGRect(x: 0, y: 372, width: cell.frame.width, height: 42)
cell.expandArrow.setBackgroundImage(UIImage(named: "ok2"), for: .normal)
}, completion: { result in
UIView.animate(withDuration: 0.2, animations: {
cell.detailView.alpha = 1
})
})
}
else {
UIView.animate(withDuration: 0.25, animations: {
cell.detailView.alpha = 0
}, completion: { result in
UIView.animate(withDuration: 0.2, animations: {
cell.expandArrow.setBackgroundImage(UIImage(named: "ok"), for: .normal)
cell.bottomView.frame = CGRect(x: 0, y: 124, width: cell.frame.width, height: 42)
})
})
}
return cell
}

当我展开单元格时,行也展开。 我的实现有什么问题? 谢谢

发生这种情况是因为您在iPad上显示单元格时似乎使用(self.view.frame.size.width - 25 - 12 - 12) / 2作为单元格的宽度。

仅针对 iPad 将计算值除以 2 可为 UICollectionView 提供足够的空间来显示同一行中的多个单元格。对于其他设备,您没有此除以 2,这只允许在一行中显示 1 个单元格。

因此,您必须更新计算以删除除法 2,或者,如果对于 iPad,您只需要单元格是计算值的一半,请实现最小项间距委托方法:

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
if Constants.isPad {
// Replace this with whatever that suits your need.
return 70.0
} else {
// Replace this with whatever that suits your need.
return 10.0
}
}

这将为两个连续的项目提供足够的空间,以便仅在一行中显示 1 个项目。您可以修改上述值以使单元格按您想要的方式显示。

最新更新