【问题标题】:Radio Button Not Working In ColectionView Cell , If I select One Button another Buttons aren't Deselecting单选按钮在 CollectionView 单元格中不起作用,如果我选择一个按钮,其他按钮不会取消选择
【发布时间】:2021-12-24 18:25:47
【问题描述】:

This Is My Struct For Image 并且是否选择了图像。

struct TeamSelected {
var logoImage: String
var isImageSelected: Bool }

这是检查选择的变量

var selection = Set<Int>()

我的单元格在 indexpath 方法中的行...

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let teamSelection : TeamSelectionCollectionViewCell = self.teamCollectionView.dequeueReusableCell(withReuseIdentifier: "teamCell", for: indexPath) as! TeamSelectionCollectionViewCell
    let index = indexPath.row
    teamSelection.logoImage.image = UIImage(named: teamSelectionList[index].logoImage)
    let isImageSelected = selection.contains(index)
    teamSelection.logoButton.isSelected = isImageSelected
    teamSelection.logoButton.setImage(
        UIImage(named: isImageSelected ? "ic_radio_selected" : "ic_radio_normal"),
        for: UIControl.State.normal
    )

    teamSelection.logoButton.tag = indexPath.row
    teamSelection.logoButton.addTarget(self, action: #selector(logoButtonTapped), for: .touchUpInside)
    teamSelection.seperatorView.isHidden = indexPath.row == 2 || indexPath.row == self.teamSelectionList.count - 1 ? true : false
    return teamSelection

}

这是按钮目标功能...

  @objc func logoButtonTapped(sender: UIButton){
    let index = sender.tag
    if (selection.contains(index)){
        selection.remove(index)
    } else {
        selection.insert(index)
    }
    self.teamCollectionView.reloadData()
}[![Here's My simulator Image, As You Can See if select A button another button is not Deselcting.][1]][1]

【问题讨论】:

    标签: ios swift objective-c uicollectionview uicollectionviewcell


    【解决方案1】:

    如果你只想选择一个,你基本上可以这样做:

    @objc func logoButtonTapped(sender: UIButton){
        let index = sender.tag
        selection.removeAll()
        selection.append(index)
        self.teamCollectionView.reloadData()
    }
    

    这种条件(selection.contains(index)) 仅在索引是selection 数组的一部分时才有效,因此当您添加新的时,旧的不会删除

    【讨论】:

    • 它正在工作,我将 var selection = Set() 更改为 var selection = [Int]()。非常感谢。
    猜你喜欢
    • 1970-01-01
    • 2015-02-27
    • 2012-09-22
    • 2011-11-05
    • 1970-01-01
    • 2021-09-01
    • 2012-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多