Search code examples
ioscheckboxswift3uibutton

Custom checkbox in swift 3


am new to swift,

I had two check box buttons on view controller, when click single check box button(Indvidual) it's check and uncheck working fine, but my aim is when I check "PICK" checkBox button uncheck the "Drop Check Box"

image

if I can select PickUP checkBox Drop should uncheck if select Drop CheckBox PickUP Should uncheck but its not happening its selecting Both

image

this is my code for single check

@IBAction func PushButtonClick(_ sender: UIButton) {

        let buttontag = sender.tag


        if isChecked {
            sender.setImage(UIImage(named:"check1"), for: .normal)
            print("checked")


            isChecked = false
        }
        else {
            sender.setImage( UIImage(named:"uncheck1"), for: .normal)
            isChecked = true
            print("uncheck")

        }
    }

    @IBAction func DropButtonClick(_ sender: UIButton) {


        if isChecked {
            sender.setImage(UIImage(named:"check1"), for: .normal)
            print("checked")
            isChecked = false
        }
        else {
            sender.setImage( UIImage(named:"uncheck1"), for: .normal)
            isChecked = true
            print("uncheck")

        }

    }

if one check box check check other check box Is unchecked how to over come this problem........


Solution

  • step-1

    create one button array for store the buttons

    var buttonscheck = [UIButton]()
    

    step-2

    on page load add the buttons to that array, for e.g

     override func viewDidLoad() {
        super.viewDidLoad()
       buttonscheck.append(btnPick)
       buttonscheck.append(btnDrop)
    }
    

    as well as create the common func for both buttons, for e.g

     @IBAction func PushButtonClick(_ sender: UIButton) {
    

    step-3

    before assign the check remove the previous selection of your UIbuttons, for e.g

     @IBAction func PushButtonClick(_ sender: UIButton) {
    
        // clear previous selection of your buttons
        for getbutton in buttonscheck {
         getbutton.setImage( UIImage(named:"uncheck1"), for: .normal)
        } 
      // finally set the selected image for your button and it will hold the current button
       sender.setImage(UIImage(named:"check1"), for: .normal)
     }