Devan Devan - 3 months ago 15
iOS Question

Swift: How to display result to Label based on button clicks

I have four buttons in my ViewControllers which act as checkboxes. When the user clicks on the checkbox buttons and click on the submit button below, I want to display the results to a Label based on the number of checkboxes selected. For example, If two check boxes are selected, The label text will be "50% selected". Can someone please help me on how can I do it.

Answer
// To maintain count of number of checkbox buttons selected

var checkCount: Int = 0   

@IBAction func CheckBox_1_Selected(sender: UIButton) {

if (sender.selected)
{

  // If  CheckBox_1 already selected, then decrement count

  checkCount = checkCount - 1

}
else
{

   // If  CheckBox_1 selected, then increment count

   checkCount = checkCount + 1

}

}

@IBAction func CheckBox_2_Selected(sender: UIButton) {

 if (sender.selected)
{

   // If  CheckBox_2 already selected, then decrement count

   checkCount = checkCount - 1

}
else
{

    // If  CheckBox_2 selected, then increment count

   checkCount = checkCount + 1
}

}

@IBAction func CheckBox_3_Selected(sender: UIButton) {

if (sender.selected)
{

   // If  CheckBox_3 already selected, then decrement count

   checkCount = checkCount - 1
}
else
{

  // If  CheckBox_3 selected, then increment count

   checkCount = checkCount + 1
}

}

@IBAction func CheckBox_4_Selected(sender: UIButton) {

if (sender.selected)
{

   // If  CheckBox_4 already selected, then decrement count

   checkCount = checkCount - 1
}
else
{

    // If  CheckBox_4 selected, then increment count

   checkCount = checkCount + 1
}

}

@IBAction func submitAction() {


countLabel.text = NSString(format:" %d % selected", checkCount * 25)

checkCount = 0

}
Comments