嗨,我正在使用 UICollectionview 水平布局开发社交网络应用程序,每当我的应用程序启动 Collection View 时,最多会加载 5 个单元格,然后如果我滑动第 5 个单元格,那么此时只会分配第 6 个单元格内存。同样的方式将第 6 个单元格滑动到第 7 个单元格。那么,我该如何实现这个过程
提前感谢您的任何建议
最佳答案
您需要向您的collectionView添加滑动手势识别器:
UISwipeGestureRecognizer *swipeGesture = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleSwipeGesture:)];
swipeGesture.direction = UISwipeGestureRecognizerDirectionUp;
[collectionView addGestureRecognizer:swipeGesture];
然后,在handleSwipeGesture:中处理滑动以分配单元格。
-(void) handleSwipeGesture:(UISwipeGestureRecognizer *) sender
{
...
}
您可以将滑动方向设置为任何您想要使用的方向,这个是向上配置的。
这几乎就是全部内容了。主要的是你不希望方向与滚动方向滑动冲突,因为我认为没有一个干净的方法来处理这个问题。当您水平滚动时,即为滑动,因此您需要使用向上/向下滑动方向。
要附加到单元格(以捕获单个单元格上的手势),我大多数时候都是通过以下方法对简单的 Collection View 执行此操作:
- (UICollectionViewCell *)collectionView:(UICollectionView *)collView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
...
UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(handleLongPress:)];
[cell addGestureRecognizer:longPressGestureRecognizer];
...
}
(这是长按,但其工作方式相同)。如果将其放入单元格中,您需要在单元格上放置一个标签,然后在处理程序中引用该标签以找出它来自哪个单元格:
这是上述内容之一:
- (void) handleLongPress: (UILongPressGestureRecognizer *) sender
{
if (sender.state != UIGestureRecognizerStateBegan)
return;
CGPoint p = [sender locationInView: collectionView];
NSIndexPath *indexPath = [collectionView indexPathForItemAtPoint:p];
if (indexPath != nil)
{
UICollectionViewCell* cell = [collectionView cellForItemAtIndexPath:indexPath];
if (cell)
{
int indexOfItem = cell.tag;
NSLog(@"Selected item = %d", indexOfItem);
}
}
至少沿着这条线做一些事情......
关于ios - CollectionView Cell 滑动执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23509121/