我正在尝试以编程方式在 UICollectionView 的每个单元格中创建一个按钮;但是,只有第一个按钮可见。我尝试添加打印语句来查看我的单元格有哪些 subview 并且按钮存在,但它没有出现在屏幕上。
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "collectionCell", for: indexPath)
// Configure the cell
let button = UIButton(frame: cell.frame)
button.addTarget(self, action: #selector(cellClicked), for: UIControlEvents.touchUpInside)
button.backgroundColor = UIColor.red
button.tag = indexPath.row
cell.addSubview(button)
print(cell.subviews)
return cell
}
此外,我在单击按钮时添加了一条打印语句,并且仅显示第一个按钮并打印出 0。
@IBAction func cellClicked(sender: UIButton) {
print(sender.tag)
}
非常感谢任何帮助。
最佳答案
在数据源中添加按钮是非常糟糕的,因为当单元格被重用时,将会创建新的按钮。如果您使用Interface Builder,请直接添加按钮。并且您可以调整它们的属性。您还可以定义自定义单元,只需按住 CTRL 键并拖动导出即可。或者在 Collection View 的委托(delegate)中处理选择。
optional public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)
另一个解决方案是在单元格的awakeFromNib()
中添加按钮,该按钮只会被调用一次。
关于ios - 多个按钮未出现在 UICollectionViewCell 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45024572/