UICollectionviewcell 在启动交互移动并使用自定义布局重新排序后消失
Posted
技术标签:
【中文标题】UICollectionviewcell 在启动交互移动并使用自定义布局重新排序后消失【英文标题】:UICollectionviewcells disappear after initiating interactive movement and re-order with custom layout 【发布时间】:2016-09-19 15:47:52 【问题描述】:我有一个带有自定义布局的UICollectionview
作为UIViewcontroller
的子视图。我想拖动我的单元格并让集合视图在被拖动的单元格移动到未拖动的单元格的边界时重新排序单元格。当您使用集合视图时会提供此功能。但是,一旦我添加了自己的布局,单元格在启动交互移动后开始消失。
这就是我设置 customFlow 布局的方式:
private var frames = [CGRect(x: 0.0, y: 0.0, width: 40.0, height: 40.0),//0
CGRect(x: 40.0, y: 0.0, width: 40.0, height: 40.0),//1
CGRect(x: 80.0, y: 0.0, width: 40.0, height: 40.0),//2
CGRect(x: 100.0, y: 0.0, width: 40.0, height: 40.0),//3
CGRect(x: 120.0, y: 0.0, width: 40.0, height: 40.0)]//4
private var cache = [NSIndexPath:UICollectionViewLayoutAttributes]()
override func prepareLayout()
super.prepareLayout()
for item in 0 ..< collectionView!.numberOfItemsInSection(0)
let indexPath = NSIndexPath(forItem: item, inSection: 0)
let attributes = UICollectionViewLayoutAttributes(forCellWithIndexPath: indexPath)
attributes.frame = frames[item]
cache[indexPath] = attributes
override func collectionViewContentSize() -> CGSize
return UIScreen.mainScreen().bounds.size
override func layoutAttributesForElementsInRect(rect: CGRect) -> [UICollectionViewLayoutAttributes]?
var layoutAttributes = [UICollectionViewLayoutAttributes]()
for attributes in cache.values
if CGRectIntersectsRect(attributes.frame, rect)
layoutAttributes.append(attributes)
return layoutAttributes
override func layoutAttributesForInteractivelyMovingItemAtIndexPath(indexPath: NSIndexPath, withTargetPosition position: CGPoint) -> UICollectionViewLayoutAttributes
let attribute = cache[indexPath]
attribute!.center = position
return attribute!
这就是我启动交互动作的方式:
func handleLongPressForCollection(gesture: UILongPressGestureRecognizer)
switch(gesture.state)
case UIGestureRecognizerState.Began:
guard let selectedIndexPath = self.CollectionView.indexPathForItemAtPoint(gesture.locationInView(self.collectionView)) else
break
CollectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath)
case UIGestureRecognizerState.Changed:
collectionView.updateInteractiveMovementTargetPosition(gesture.locationInView(CollectionView))
case UIGestureRecognizerState.Ended:
collectionView.endInteractiveMovement()
default:
collectionView.cancelInteractiveMovement()
break
我不太了解invalidatelayout
。我想我需要它来解决这个问题?我试过覆盖函数invalidationContextForEndingInteractiveMovementOfItemsToFinalIndexPaths
但我仍然得到相同的结果。
【问题讨论】:
【参考方案1】:我遇到了同样的问题,发现原因是我没有在被覆盖的函数中调用父级。从您的代码中,我看到您没有从 layoutAttributesForElementsInRect
函数中的父级检索当前布局属性。您必须在该方法的第一行执行此操作:var layoutAttributes = super.layoutAttributesForElements(in: rect)
【讨论】:
以上是关于UICollectionviewcell 在启动交互移动并使用自定义布局重新排序后消失的主要内容,如果未能解决你的问题,请参考以下文章
UICollectionviewcell 在启动交互移动并使用自定义布局重新排序后消失
如何启动 UINavigationController 推送以响应对 UICollectionViewCell 的点击
在 UICollectionViewCell 上设置 .reuseIdentifier