将故事板中的手势添加到单元格

时间:2013-03-13 06:07:11

标签: iphone ios objective-c uigesturerecognizer

我已在故事板中初始化了longPressGesture,我想将其添加到collectionView中的单元格中。

问题是:该手势仅适用于collectionView

中最后添加的单元格

这是我的代码:

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
     MyCollectionCell *cell = (MyCollectionCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];
    [cell addGestureRecognizer:longPressGesture];
    return cell;
}

.h文件:

IBOutlet UILongPressGestureRecognizer *longPressGesture;

1 个答案:

答案 0 :(得分:1)

如果您的手势目标方法对所有单元格执行相同操作,则每次创建新UILongPressGesture并将其分配给UICollectionView的单元格

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {

     MyCollectionCell *cell = (MyCollectionCell*)[collectionView dequeueReusableCellWithReuseIdentifier:@"MyCell" forIndexPath:indexPath];

     UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc] 
                                          initWithTarget:self action:@selector(handleGesture:)];
     longPressGesture.minimumPressDuration = 1.5; 

    [showUserMap addGestureRecognizer:lpgr];

    [cell addGestureRecognizer:longPressGesture];
    return cell;
}