嵌套UITableViewCell的UICollectionViewCell内UIButton点击无响应问题
核心原因:按钮完全超出Cell可视范围
你的DashboardCollectionViewCell里,按钮btnRateMore的约束设置错误,导致它根本不在Cell的可点击区域内:
- 你给UICollectionView设置的itemSize是170x170,也就是每个Cell的大小固定为170x170
posterImage的宽度设为170,还额外加了leading=20、trailing=-20的边距,这本身就让图片超出了Cell边界- 按钮的leading约束是
posterImage.trailing + 30,算下来按钮的起始位置是170+30=200,远超Cell的170宽度,等于按钮完全在Cell外部,自然无法响应点击。
一步步修复
1. 调整按钮约束,让它显示在Cell内部
把按钮放在图片的合理位置,比如覆盖在图片底部,修改DashboardCollectionViewCell里的约束代码:
NSLayoutConstraint.activate([ // 修正图片约束,让它完全适配Cell posterImage.leadingAnchor.constraint(equalTo: contentView.leadingAnchor), posterImage.topAnchor.constraint(equalTo: contentView.topAnchor), posterImage.trailingAnchor.constraint(equalTo: contentView.trailingAnchor), posterImage.bottomAnchor.constraint(equalTo: contentView.bottomAnchor), // 按钮约束:放在图片底部,左右留边,高度固定 btnRateMore.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 10), btnRateMore.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -10), btnRateMore.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -10), btnRateMore.heightAnchor.constraint(equalToConstant: 40) ])
2. 删除重复添加的Target
你在两个地方给按钮绑定了点击事件:一个是DashboardCollectionViewCell的初始化方法里,另一个是DashboardCollectionViewTableViewCell的collectionView(_:cellForItemAt:)方法里。重复绑定会导致点击时多次触发逻辑,且Cell复用时容易出问题,保留Cell内部的绑定即可,删掉下面这段代码:
cell.btnRateMore.addTarget(self, action: #selector(showMore(_:)), for: .touchUpInside)
3. 确保交互属性正常开启
虽然UIButton默认允许交互,但可以显式设置避免意外情况:
lazy var btnRateMore: ButtonRating = { let btn = ButtonRating() // ... 其他原有设置 btn.isUserInteractionEnabled = true return btn }()
同时确保Cell及其contentView也开启交互:
override init(frame: CGRect) { super.init(frame: frame) contentView.isUserInteractionEnabled = true self.isUserInteractionEnabled = true // ... 其他初始化代码 }
4. 修复Cell复用的状态问题
在DashboardCollectionViewCell的prepareForReuse方法里重置按钮的隐藏状态,避免Cell复用后按钮状态错乱:
override func prepareForReuse() { super.prepareForReuse() posterImage.image = nil btnRateMore.isHidden = true // 重置为隐藏状态,后续在cellForItem里按需设置显示 }
做完以上调整,按钮就能正常显示在Cell内部,点击事件也会正常响应了。
内容的提问来源于stack exchange,提问作者KwameB
相关产品推荐
相关产品推荐

