2015-10-26 104 views
1

我想在不使用Storyboard的情況下以編程方式在Swift中以編程方式構建一個CollectionView。我能夠將單擊手勢事件添加到單元格中。以編程方式在UICollectionViewCell SWIFT中添加多個按鈕+接收touchUpInside事件

但是,當我向UICollectionViewCell的contentView添加一組按鈕時,按鈕不會收到任何觸摸事件。

內部控制

let sampleCollectionView = UICollectionView(frame: (..), collectionViewLayout: layout) 

//Register the UICollectionViewCell inside UICollectionView 
sampleCollectionView.registerClass(sampleCollectionViewCell.self, forCellWithReuseIdentifier: "sampleCell") 

//Add Tap Gesture event to the cell area 
let tap = UITapGestureRecognizer(target: self, action: "handleTapForCell:") 
sampleCollectionView.addGestureRecognizer(tap) 

func handleTapForCell(recognizer: UITapGestureRecognizer){ 
    //I can break in here 
} 

內CollectionViewCell

class sampleCollectionViewCell: UICollectionViewCell 
{ 

override init(frame: CGRect) { 
    var buttonBack = UIButton(type: .Custom) 
    buttonBack.addTarget(self, action: "actionGoBack:", forControlEvents: UIControlEvents.TouchUpInside) 
    .. 
    self.contentView.addSubview(buttonBack) 
} 

func actionGoBack(sender: UIButton){ 
    //I want to get my touch action break in here when I tap right inside the button but it won't 
}   
} 

是CollectionViewCell適合接受多種類型的龍頭作用(對細胞內整個小區與多按鍵敲擊)?

這裏是我試過到目前爲止:

  1. 停用點手勢上的CollectionView,仍然沒有收到事件
  2. 無需添加點擊事件到按鈕,我試圖找到裏面的水龍頭的「位置」單元格,然後檢查它是否位於按鈕的邊界,如果是,則觸發一個事件。當我嘗試添加動畫或滾動時,我發現這項工作變得越來越麻煩。

感謝您的建議和幫助。

+0

你爲什麼添加一個輕拍識別器到細胞? UICollectionView具有didSelect的回調函數嗎? – Moriya

+0

是的,我在單元級別互換了didSelect/tapGesure - 對按鈕沒有影響。 –

回答

3

您可以設置手勢識別器不會阻止觸摸在子視圖

gestureRecognizer.cancelsTouchesInView = false 

您還可以實現UIGestureRecognizerDelegate並設置自己作爲代表。然後你就可以實現shouldReceiveTouch

optional public func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool 

在那裏,你可以檢查其觀點針對性和返回false,如果你不想在細胞手勢識別觸控反應。

+0

輝煌。只需設置水龍頭。 cancelsTouchesInView = false,讓事件識別(我必須點擊兩次)。我現在要做的就是從可再生的東西中找到確切的細胞來處理我的事件。謝謝! –

相關問題