UICollectionViewCell with UIButton复选框 - 在

时间:2016-12-07 19:10:48

标签: ios swift checkbox uibutton

我有UICollectionView和UIButton作为复选框和名字和姓氏的标签。 UIButton位于UICollectionViewCell内。我的问题是下一个:

我需要在时间选中一个复选框,如果按下了下一个,则应取消选择之前的复选框。我试图弄清楚UIButton的indexPath,unfortunetley没有运气。我将不胜感激。

这是checkBox类:

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

2 个答案:

答案 0 :(得分:0)

有很多方法可以解决这个问题,但有一种方法是在视图控制器中保留一个变量,并使用您的参与方列表来存储用户选择的indexPath。

所以假设你有这样一个属性:

var selectedIndex: IndexPath?

然后在cellForItem:中,您只需检查当前indexPath是否等于selectedIndex,如果是,则将该框标记为已选中。

每当用户选中一个复选框时,只需将selectedIndex更新为新索引,然后在收藏视图上调用reloadData()

答案 1 :(得分:0)

尝试使用pod作为集合视图复选框,例如TNSwiftyCheckboxGroup https://cocoapods.org/?q=lang%3Aswift%20checkbox%20 enter image description here

相关问题