我想在不使用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適合接受多種類型的龍頭作用(對細胞內整個小區與多按鍵敲擊)?
這裏是我試過到目前爲止:
- 停用點手勢上的CollectionView,仍然沒有收到事件
- 無需添加點擊事件到按鈕,我試圖找到裏面的水龍頭的「位置」單元格,然後檢查它是否位於按鈕的邊界,如果是,則觸發一個事件。當我嘗試添加動畫或滾動時,我發現這項工作變得越來越麻煩。
感謝您的建議和幫助。
你爲什麼添加一個輕拍識別器到細胞? UICollectionView具有didSelect的回調函數嗎? – Moriya
是的,我在單元級別互換了didSelect/tapGesure - 對按鈕沒有影響。 –