【发布时间】:2018-09-11 21:32:25
【问题描述】:
我在 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 吗?还是别的什么?
【问题讨论】:
-
connectButton也没有被调用吗?您在界面生成器中正确连接了吗? -
它没有被调用,是的,我已经仔细检查了它在 IB 中是否正确连接。
-
创建按钮的委托方法
-
您应该尝试将您的收藏视图及其父滚动视图的 clipsToBounds 属性设置为
true。由于您的集合视图位于滚动视图中,因此滚动视图的大小可能具有挑战性,也许您可以看到单元格,但父视图的大小不正确,从而弄乱了响应链。 -
@DirtyHenry 都已经在 IB 中将 Clip To Bounds 设置为 true。
标签: ios swift uicollectionview uicollectionviewcell swift4