2014-12-30 87 views
0

我有一個全屏水平collectionview。如何將手勢識別器添加到collectionview單元格中的uiview中

  1. 滾動禁用
  2. 分頁被啓用,也有對未來分頁/分組按鈕。

在我的collectionview cell中,我有一個標籤,當用戶向左/向右滑動時,我想識別它。 我將標記添加到標籤後沒有任何反應。

CODE:

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切換目標自我,它仍然無法正常工作。

感謝

回答

0

我的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 
} 
+0

謝謝, 我得到一個無法識別的選擇器發送到實例。 – ilan

+0

您是否在視圖控制器中實現了'test:'?你需要否則你會得到這樣的錯誤。無論您設置了「目標」,都必須實現該選擇器。 – trevorj

+0

效果很好,忘了補充:去測試。 – ilan

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

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