简体   繁体   中英

how to add a gesture recogniser to a uiview in a collectionview cell

I have a full screen horizontal collectionview.

  1. scrolling is disabled
  2. paging is enabled, there are next/prev buttons for the paging.

In my collectionview cell i have a label that i want to recognise when the user swipes it to the left/right. After i added the gesture to the label nothing happens.

CODE:

collectionViewCell:

func addGesture(){
    let right = UISwipeGestureRecognizer(target: myLabel, action: "test")
    right.direction = UISwipeGestureRecognizerDirection.Left
    answer.addGestureRecognizer(right)
}

view controller:

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("formQuestionCell", forIndexPath: indexPath) as QuestionCell

    cell.addGesture()

    return cell
}

I also tries to switch the target from myLabel to self and it still doesn't work.

Thanks

 UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                         initWithTarget:self action:@selector(clickEventOnImage:)];

[tapRecognizer setNumberOfTapsRequired:1];
[tapRecognizer setDelegate: self];
cell.uiviewelement.userInteractionEnabled = YES;
[cell.uivielement addGestureRecognizer:tapRecognizer];

I would move the addGesture code to the view controller so that you can handle the swipes in the view controller as well.

Change

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell

to

func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCellWithReuseIdentifier("formQuestionCell", forIndexPath: indexPath) as QuestionCell

    let right = UISwipeGestureRecognizer(target: self, action: Selector("test:"))
    right.direction = UISwipeGestureRecognizerDirection.Left
    cell.answer.addGestureRecognizer(right) // I am assuming 'answer' is an outlet to the label you want to add a gesture recognizer to in the QuestionCell class

    return cell
}

and then you need to implement test: in the view controller as well (because you set the target to self ):

func test(gestureRecognizer: UISwipeGestureRecognizer) {
    // Deal with swipe
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM