2016-01-26 82 views
1

我一直在尝试这个好几个小时没有运气。我有一个UICollectionView collectionView。集合视图基本上是一个列表,最后一个单元格始终是一个带有大加号的单元格,用于添加另一个项目。我已经启用了以下的重新排序。我想要做的是当我开始交互式移动时,加号单元消失,然后当用户完成编辑时,它再次出现。这是代码我有一个基本的版本:暂时隐藏UICollectionView中的单元格Swift iOS

func handleLongGesture(gesture: UILongPressGestureRecognizer) { 

     switch(gesture.state) { 

     case UIGestureRecognizerState.Began: 

      ... 

      self.collectionView.beginInteractiveMovementForItemAtIndexPath(selectedIndexPath) 

      removeAddCell() 

     case UIGestureRecognizerState.Changed: 


     case UIGestureRecognizerState.Ended: 

      ... 


      collectionView.endInteractiveMovement() 
      replaceAddCell() 

     default: 

      collectionView.cancelInteractiveMovement() 
     } 
    } 


    func removeAddCell(){ 

     print("Reloading data - removing add cell") 

     data_source.popLast() 

     self.collectionView.reloadData() 

    } 

    func replaceAddCell(){ 

     print("Reloading data - replacing add cell") 

     data_source.append("ADD BUTTON") 

     self.collectionView.reloadData() 

    } 

这是非常粗糙的伪代码,但我甚至不能这样做的最简单的工作。使用我拥有的代码,在从数据源中删除项目之后引用UICollectionViewCell的行中,它给了我可怕的“致命错误:意外地发现了零,同时展开可选值”。

如果有人做过这样的事情可以分享他们的方法,我会非常感激!谢谢!

-Bryce

+0

而不是试图将其删除,为什么不把它藏起来使用透明度(阿尔法),并关闭用户交互?对于加号来说,这可能是一种更好的用户体验,可以暗淡而不是完全消失。如果你开始拖动某个东西而另一个东西消失,它可能看起来像是出了问题。 – Michael

+0

可以使用告诉我们哪一行有致命错误? –

+0

我试图用alpha 0隐藏它,但单元格仍然存在,所以如果用户从顶部向底部移动一个单元格,则在添加单元格的第二个到最后一个位置存在间隙。 @迈克尔 – brycejl

回答

0

我已经做了这样的事情。集合视图的数据源跟踪BOOL以确定是否显示添加项目单元格。然后拨打insertItemsAtIndexPaths:deleteItemsAtIndexPaths:,使添加项目单元出现和消失。我实际上使用编辑按钮切换模式。但是,您可以调整此代码以使用您的手势识别器。

基本代码:

self.editing = !self.editing; // toggle editing mode, BOOL that collection view data source uses 
NSIndexPath *indexPath = [self indexPathForAddItemCell]; 
if (!self.editing) { // editing mode over, show add item cell 
    if (indexPath) { 
     [self.collectionView insertItemsAtIndexPaths:@[indexPath]]; 
    } 
} 
else { // editing mode started, delete add item cell 
    if (indexPath) { 
     [self.collectionView deleteItemsAtIndexPaths:@[indexPath]]; 
    } 
} 
0

你可以做这样的事情:

func longPressed(sender: UILongPressGestureRecognizer) { 
    let indexPath = NSIndexPath(forItem: items.count - 1, inSection: 0) 
    let cell = collectionView.cellForItemAtIndexPath(indexPath) as! YourCollectionViewCell 
    switch sender.state { 
    case .Began: 
     UIView.animateWithDuration(0.3, animations: { 
      cell.contentView.alpha = 0 
     }) 

    case .Ended: 
     UIView.animateWithDuration(0.3, animations: { 
      cell.contentView.alpha = 1 
     }) 

    default: break 
    } 
} 

这种方式也随之逐渐消失,而不是硬生生。

相关问题