我有 UICollectionView,其中 UIButton 作为复选框以及名字和姓氏的标签。 UIButton 位于 UICollectionViewCell 内部。我的问题是:
我需要一次选中一个复选框,如果按下下一个,则应取消选择上一个。我试图找出 UIButton 的 indexPath,不幸的是没有运气。我将不胜感激的帮助。
这是复选框类:
let checkedImage = UIImage(named: "1x_checked")! as UIImage
let uncheckedImage = UIImage(named: "1x_unchecked")! as UIImage
// Bool property
var isChecked: Bool = false {
didSet{
if isChecked == true {
self.setImage(checkedImage, for: .normal)
} else {
self.setImage(uncheckedImage, for: .normal)
}
}
override func awakeFromNib() {
self.addTarget(self, action: #selector(buttonClicked(sender:)), for: .touchUpInside)
self.isChecked = false
}
func buttonClicked(sender: UIButton) {
if sender == self {
isChecked = !isChecked
ViewController:
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return listOfPartys.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: izborStrankeCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! izborStrankeCollectionViewCell
cell.label.text = listOfPartys[indexPath.row]
return cell
最佳答案
有很多方法可以解决这个问题,但一种方法是在 View Controller 中保留一个变量,并在派对列表中存储用户选择的indexPath。
假设您有这样的属性:
var selectedIndex: IndexPath?
然后在 cellForItem:
中,您只需检查当前的 indexPath 是否等于 selectedIndex,如果是,则将该框标记为选中。
每当用户选中某个框时,只需将 selectedIndex 更新为新索引并在 Collection View 上调用 reloadData()
即可。
关于ios - UICollectionViewCell 与 UIButton 复选框 - 一次选中一个复选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41025446/