Home > Back-end >  How to deselect all buttons when one of them is selected
How to deselect all buttons when one of them is selected

Time:12-31

I have a tableview and inside one of my rows I have buttons. I want to deselect all buttons when one is selected and change the background color to the red when button is selected. I saw lots of example but I couldn't do it in my own code.

func configure(_ modelArray : [UnitAndColors], colorTitle:String, packingTitle:String) {
    self.unitStackView.removeAllArrangedSubviews()
    self.arrayUnitsAndColor?.removeAll()
    self.arrayUnitsAndColor = modelArray
    let filteredArray = self.arrayUnitsAndColor?.unique { $0.colorDesc }
    var i : Int = 0
    filteredArray?.forEach { units in
        let vw = self.createUnits(units, tag: i)
        self.unitStackView.addArrangedSubview(vw)
        vw.snp.makeConstraints {
            $0.size.equalTo(40.0)
        }
        i = i   1
    }
}

func createUnits(_ model : UnitAndColors, tag: Int) -> UIStackView {
    let stackViewMain = UIStackView()
    stackViewMain.axis = .horizontal
    stackViewMain.spacing = 4
    
    let labelPackingUnit = UIButton()
    labelPackingUnit.backgroundColor = Colors().colorWhite
    labelPackingUnit.tag = tag
    labelPackingUnit.setTitleColor(Colors().colorRed, for: .normal)
    labelPackingUnit.addTarget(self, action: #selector(selectUnit(_:)), for: .touchUpInside)
    labelPackingUnit.titleLabel?.font = UIFont.fontBold16
    labelPackingUnit.contentHorizontalAlignment = .center
    labelPackingUnit.setBorder(width: 1, color: Colors().colorRed)
    labelPackingUnit.setCornerRound(value: 20.0)
    labelPackingUnit.setTitle(model.unitDesc, for: .normal)
    stackViewMain.addArrangedSubview(labelPackingUnit)
    labelPackingUnit.snp.makeConstraints {
        $0.size.equalTo(40)
    }
    return stackViewMain
}

@objc private func selectButton(_ sender : UIButton) {
    let tag : Int = sender.tag
    guard let model : UnitAndColors = self.arrayUnitsAndColor?.filter({ $0.colorDesc == selectedColorName })[tag] else { return }
    selectedUnit = model.unitDesc ?? ""
    delegate?.changePrice(selectedPrice: model.modelPrice, arrayUnitsAndColor ?? [])
}

CodePudding user response:

It's pretty frustrating to understand what's happening in your code, but I think that's what you're looking for:

@objc private func selectButton(_ sender : UIButton) {
        let tag : Int = sender.tag
        guard let model: UnitAndColors = self.arrayUnitsAndColor?.filter({ $0.colorDesc == selectedColorName })[tag] else { return }
        selectedUnit = model.unitDesc ?? ""
        
        for stackView in unitStackView.arrangedSubviews as? [UIStackView] ?? [] {
            guard let button = stackView.arrangedSubviews.first as? UIButton else {
                return
            }
            button.isSelected = false
            button.backgroundColor = .clear
        }
        selectedUnit.isSelected = true
        selectedUnit.backgroundColor = .red
        
        delegate?.changePrice(selectedPrice: model.modelPrice, arrayUnitsAndColor ?? [])
    }

CodePudding user response:

var selectedRows: [Int] = [Int]()

override func viewDidLoad() {
        super.viewDidLoad()
        self.tableView.allowMultipleSelection = true
}

func selectAll(){
for i in 0..<totalRows.count{
          selectedRows.append(i)
          let indexPath = IndexPath(row: i, section: 0)
          self.tableView.selectRow(at: indexPath, animated: true, scrollPosition: .none)
          }
}

func deselectAll(){
for i in 0..<totalRows.count{
                selectedRows.append(i)
                let indexPath = IndexPath(row: i, section: 0)
                self.tableView.deselectRow(at: indexPath, animated: true)
                }
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
       
            selectedRows.append(indexPath.row)
            print(selectedRows)
            
        }
    }
    
    func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
       
            if let index = selectedRows.firstIndex(of: indexPath.row) {
                selectedRows.remove(at: index)
            }
            print(selectedRows)
          
            if selectedRows.isEmpty{
               
            }
        }
    }
class TableViewCell: UITableViewCell{
 override func setSelected(_ selected: Bool, animated: Bool) {
            super.setSelected(selected, animated: animated)
            if (selected) {
                print("selected")
                contentView.backgroundColor = .red
              } else {
                  contentView.backgroundColor = .red
              }
        }
}
  • Related