单击后如何删除按钮的选定状态?

时间:2019-06-30 17:29:20

标签: ios swift uicollectionview

我有一个应用程序,其中有类别收集视图,并且在每个单元格中都有一个按钮,选择该按钮后需要更改其图像。单击该按钮时,将附加选定的ID,当我按下对勾按钮时,我转到另一个屏幕,它向我显示与该类别有关的所有数据。当我取消选择类别并按下按钮时,它仍然显示我不需要的该类别的数据。谁能帮助我解决这个问题?

我的应用的屏幕截图:

screenshot for my app

到目前为止,我尝试过的代码是:

cellforrow方法:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    if selectedBtnIndex == 1{
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "CategoryCell1", for: indexPath) as! CategoryCell1

        let dict = categoryData[indexPath.row]

        if let catName = dict.name, catName.count != 0 {
            cell.categoryName.text = catName
        }

        if let catOffersCount = dict.count {

            if catOffersCount == 1 {
              cell.catOfferCount.text = "\(catOffersCount)"+" "+"Offer"
            }else {
                cell.catOfferCount.text = "\(catOffersCount)"+" "+"Offers"
            }
        }

        cell.categoryImage.image = arrCategoryImages[indexPath.row]

        cell.btn_click.tag = indexPath.row
        cell.btn_click.addTarget(self, action: #selector(self.click_Category), for: .touchUpInside)

        if selectedIds.contains(categoryData[indexPath.row].ID!) {
            cell.btn_click.setImage(#imageLiteral(resourceName: "image_checked"), for: .normal)
            cell.btn_click.isSelected = true
        }else {
            cell.btn_click.setImage(#imageLiteral(resourceName: "image_unchecked"), for: .normal)
            cell.btn_click.isSelected = false
        }

        return cell

按钮添加目标功能:

@objc func click_Category(sender: UIButton!) {
    if sender.isSelected == true {
        selectedIds.append(categoryData[sender.tag].ID!)
        sender.setImage(#imageLiteral(resourceName: "image_checked"), for: .normal)
        sender.isSelected = false
    } else {
        selectedIds = selectedIds.filter{ $0 != sender.tag }
        sender.setImage(#imageLiteral(resourceName: "image_unchecked"), for: .normal)
        sender.isSelected = true
    }
}

1 个答案:

答案 0 :(得分:0)

发布的代码主要存在两个错误。这些逻辑错误位于 click_Category 函数中。错误是:

1。使用 sender.isSelected 切换UIButton图像的操作不正确。 2.“ if”语句的第一块将ID附加在 selectedIds 数组中,但是再次单击同一UIButton取消选中它时, selectedIds 数组不会删除未选中的UIButtons ID。

以下是修改后的 click_Category 功能的代码段:

 @objc func click_Category(sender: UIButton!) {

    sender.isSelected = !sender.isSelected
    if sender.isSelected {
        selectedIds.append(categoryData[sender.tag].ID!)
        sender.setImage(UIImage(named: "image_checked"), for: .normal)
    }else {
        selectedIds = selectedIds.filter {$0 != categoryData[sender.tag].ID!}//removing the unchecked ID
        sender.setImage(UIImage(named: "image_unchecked"), for: .normal)
    }

}