我有一个 CollectionView,其中的单元格具有全宽度和动态(自动布局计算)高度。
我通过设置估计高度来做到这一点:
flowLayout.estimatedItemSize = CGSize(width: 200, height: 10)
然后在委托(delegate)方法中返回完整宽度和任意高度。
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.width, height: 10)
}
然后在单元格中执行以下操作:
override func preferredLayoutAttributesFitting(_ layoutAttributes: UICollectionViewLayoutAttributes) -> UICollectionViewLayoutAttributes {
setNeedsLayout()
layoutIfNeeded()
let size = self.systemLayoutSizeFitting(layoutAttributes.size)
var newFrame = layoutAttributes.frame
// note: don't change the width
newFrame.size.height = ceil(size.height)
layoutAttributes.frame = newFrame
return layoutAttributes
}
一切都按预期进行...单元格大小符合预期!太棒了!
现在我想添加重新排序... 我添加了一个 GestureRecognizer 并使其重新排列我的单元格..
@objc func handleLongPress(gestureRecognizer: UILongPressGestureRecognizer) {
guard let view = gestureRecognizer.view else { return }
let location = gestureRecognizer.location(in: view)
switch gestureRecognizer.state {
case .began:
guard let selectedIndexPath = collectionView.indexPathForItem(at: location) else { break }
collectionView.beginInteractiveMovementForItem(at: selectedIndexPath)
case .changed:
collectionView.updateInteractiveMovementTargetPosition(location)
case .ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
}
}
这基本上也有效...但是在重新排序期间,我的单元格会奇怪地动画...单元格有时会将其大小减小到我的大小 10,但不会让单元格自行测量。松开拖动后,它会再次工作...
我注意到,当我缓存 CollectionViewCells 的高度时,情况会好一些,但对于我以前没有见过的所有单元格,它又会是 10 点高的单元格。
为了在重新排序期间使单元格大小正确,我缺少什么?
我还有一个存在此问题的示例项目,可以在这里找到:https://www.dropbox.com/s/ya6zald4wa6kg10/CollectionViewTester.zip?dl=0
最佳答案
问题是,当对自动调整大小的单元格重新排序时,单元格大小会更改为estimatedItemSize
。
报告有开放雷达here .
关于ios - 使用全宽和动态高度单元重新排序 UICollectionView 时出现 UI 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52001918/