【问题标题】:how to add a gesture recogniser to a uiview in a collectionview cell如何将手势识别器添加到collectionview单元格中的uiview
【发布时间】:2014-12-30 08:01:17
【问题描述】:

我有一个全屏水平collectionview。

  1. 滚动已禁用
  2. 分页已启用,分页有下一个/上一个按钮。

在我的 collectionview 单元格中,我有一个标签,当用户向左/向右滑动它时我想识别它。 在我将手势添加到标签后,没有任何反应。

代码:

collectionViewCell:

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

视图控制器:

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

    cell.addGesture()

    return cell
}

我也尝试将目标从 myLabel 切换到 self ,但它仍然不起作用。

谢谢

【问题讨论】:

    标签: ios swift uigesturerecognizer uicollectionviewcell


    【解决方案1】:

    我会将addGesture 代码移动到视图控制器,以便您也可以处理视图控制器中的滑动。

    改变

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

    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
    }
    

    然后您还需要在视图控制器中实现test:(因为您将目标设置为self):

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

    【讨论】:

    • 谢谢,我收到一个无法识别的选择器发送到实例。
    • 你是否也在视图控制器中实现了test:?你需要否则你会得到这样的错误。无论你设置什么 target 都必须实现该选择器。
    【解决方案2】:
     UITapGestureRecognizer *tapRecognizer = [[UITapGestureRecognizer alloc]
                                             initWithTarget:self action:@selector(clickEventOnImage:)];
    
    [tapRecognizer setNumberOfTapsRequired:1];
    [tapRecognizer setDelegate: self];
    cell.uiviewelement.userInteractionEnabled = YES;
    [cell.uivielement addGestureRecognizer:tapRecognizer];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多