collection View Cells 交互

collectionViewCells interact

我有一个集合视图,每个单元格都有一个按钮, 我添加了一个在按下按钮时调用的 IB 动作。

我的问题是,当点击某个按钮时,我不仅想更改该按钮的背景颜色,我还想更改所有单元格中的所有按钮

我不确定如何实现这个...

谢谢。

当您按下按钮时,您应该通知您的 collectionView class 持有者(通过 delegate 模式或使用 closure)现在所有按钮都应该更改。然后你应该强制更改所有可见按钮(获取 collectionView 的所有 visibleCells 并更改按钮样式)并且在 cellForItemAtIndexPath 方法中更改现在不可见的所有其他按钮的按钮样式。

试试这样的东西

拍一张var selectedIndex : Int = -1

cellForItemAt

 cell.button.tag = indexpath.item
if selectedIndex == indexPath.item{
   cell.button.backgroundColor = UIColor.blue // New Color
}
else{
   cell.button.backgroundColor = UIColor.gray // Deafult color
}

Button Action

selectedIndex = sender.tag
collectionView.ReloadData()