簡體   English   中英

添加多個按鈕+以編程方式在UICollectionViewCell SWIFT中接收touchUpInside事件

[英]Adding multiple buttons + receiving touchUpInside event inside UICollectionViewCell SWIFT programmatically

我試圖在不使用Storyboard的情況下以編程方式在Swift中為列表構建CollectionView。 我能夠向單元格添加一個輕擊手勢事件。

但是,當我向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上禁用Tap Gesture,仍然沒有接收事件
  2. 在沒有向按鈕添加tap事件的情況下,我試圖在單元格內找到tap的“位置”,然后檢查它是否在按鈕的邊界內,如果是,則觸發事件。 當我嘗試添加動畫或滾動時,我發現這個工作有問題。

感謝您的建議和幫助。

您可以將手勢識別器設置為不阻止子視圖中的觸摸

gestureRecognizer.cancelsTouchesInView = false

您還可以實現UIGestureRecognizerDelegate並將自己設置為委托。 然后你可以實現shouldReceiveTouch

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

在那里,您可以檢查哪個視圖是目標,如果您不想對單元格手勢識別器中的觸摸作出反應,則返回false。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM