【发布时间】:2018-12-31 17:43:13
【问题描述】:
所以基本上我的问题是,当我单击集合视图单元格中存在的button 时,它应该改变按钮背景颜色的颜色。但问题是它正在改变另一个按钮的颜色。例如,如果我单击按钮 1,它会自动更改按钮 6 的颜色。
class hello: UICollectionViewCell {
@IBOutlet weak var btn: UIButton!
@IBAction func click(_ sender: Any) {
if btn.isSelected == true
{
btn.backgroundColor = UIColor.red
btn.isSelected = false
}
else{ btn.backgroundColor = UIColor.purple
btn.isSelected = true
}
}
override func prepareForReuse() {
super.prepareForReuse()
}
}
view controller file
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "happy", for: indexPath) as! hello
if cell.btn.isSelected
{
cell.btn.backgroundColor = UIColor.red
}
else{ cell.btn.backgroundColor = UIColor.purple
}
cell.btn.tag = indexPath.item
print(cell.btn.isSelected ,indexPath.row)
return cell
}
【问题讨论】:
-
不要使用
btn,而是将其替换为sender,并将发件人类型Any更改为UIButton并检查。 -
@AlishaChaudhary 你能贴出符合
UICollectionViewDataSource协议的代码吗? -
它仍然无法正常工作。在按下一个按钮时,两个按钮被按下。(0-5),(1-6),(2,7),(3-8),(4-9)
标签: ios swift uicollectionview uibutton