簡體   English   中英

CollectionView 中的按鈕不可點擊

[英]Button inside CollectionView not clickable

我在 collectionview 的自定義單元格中有一個按鈕。 集合視圖位於滾動視圖上。 出於某種原因,我無法點擊按鈕。 我已經檢查過我的所有元素都啟用了用戶交互。

這是我的收藏布局(我隱藏了一些敏感數據) 在此處輸入圖片說明

這是我的自定義集合視圖單元格:

class MyCollectionViewCell: UICollectionViewCell {

    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var connectButton: UIButton!

    var onConnectTap: (MyCollectionViewCell) -> Void)?
    @IBAction func connectButton(_ sender: Any) {
        onConnectTap?(self)
    }

    func populate(_ user: User) {
        nameLabel.text = user.name
     }
}

我有一個 xib 文件,其中一個按鈕的 Touch Up Inside 事件已連接到 connectButton IBAction。

在我的 ViewController 中:

MyCollectionView.register(UINib(nibName: "MyCollectionViewCell", bundle: nil), forCellWithReuseIdentifier: "cell") 

這是我的 ViewController 中的集合視圖函數:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell
        let user = users.values[indexPath.row]
        cell.populate(user)

        cell.onConnectTap = { (cell) in
            //do something
        }

        return cell

}

當我點擊按鈕時什么也沒有發生。 我在這里錯過了什么嗎? 滾動視圖是否有干擾? 我需要指定一個 addTarget 嗎? 或者別的什么?

在幾乎搜索了整個網絡之后,我終於找到了這個 SO 答案的評論中的解決方案: https : //stackoverflow.com/a/44908916/406322

我需要在 MyCollectionViewCell 中添加這個:

self.contentView.isUserInteractionEnabled = false

我認為細胞選擇正在劫持觸摸事件。

我面臨同樣的問題,並在花了很多時間后找到了最佳解決方案。

cell.contentView.isUserInteractionEnabled = false

但它是完美的解決方案,並且只在單元格中為 item 方法添加了一行

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = myCollectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! MyCollectionViewCell

     cell.contentView.isUserInteractionEnabled = false
     return cell
}

仔細檢查 XIB 文件的結構。 我在處理這個問題時浪費了時間(XIB 中的按鈕似乎沒有響應),因為該結構有第二個嵌入式單元,而不僅僅是一個(在我的情況下為 AboutCell)。

在此處輸入圖片說明

暫無
暫無

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

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