Home > Software design >  Changing color of uibutton
Changing color of uibutton

Time:11-19

I am trying to create a UIbutton that changes color to green when tapped and blue when deselected. My logic works however when I exit the screen it still shows blue when selected because it's the default color shown before the button is tapped. What can I do to resolve this ?

func setUpSelectDealerButton(){
    selectDealerButton.layer.cornerRadius = 5
    view.addSubview(selectDealerButton)
    selectDealerButton.setTitle( "Select Dealer" , for: .normal)
    selectDealerButton.backgroundColor = .systemBlue
    
    selectDealerButton.snp.makeConstraints{ (make) in
        make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(-16)
        make.top.equalTo(view.safeAreaLayoutGuide.snp.bottom).offset(16)
        
        make.leading.equalTo(view.safeAreaLayoutGuide.snp.leading).offset(3)
        make.trailing.equalTo(view.safeAreaLayoutGuide.snp.trailing).offset(-3)
        make.height.equalTo(50)
        make.width.equalTo(50)
    }
    selectDealerButton.addTarget(self, action: #selector(addToSelectedAccounts), for: .touchUpInside)
}

@objc func addToSelectedAccounts() {
    if let selectedAccounts = delegate?.selectedAccounts, !selectedAccounts.contains(viewModel.account) {
        delegate?.didSelect(account: viewModel.account)
    }
    
    if selectDealerButton.isSelected{
       selectDealerButton.isSelected = false
       selectDealerButton.setTitle( "Select Dealer" , for: .normal)
       selectDealerButton.backgroundColor = .systemBlue
    }
    else{
        selectDealerButton.isSelected = true
        selectDealerButton.setTitle( "Dealer Selected" , for: .normal)
        selectDealerButton.backgroundColor = .systemGreen
        GlobalMBProgressHud.sharedInstance.showGlobalHud(withSuccess: true, text: "Selected!")
    }
}

This is the screenshot: enter image description here

  • Related