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