Niroj thapa Niroj thapa - 25 days ago 21
Swift Question

Switch case in swift

These are my

UIButtons


@IBOutlet weak var btnProgressDate: UIButton!
@IBOutlet weak var btnClosedDate: UIButton!


I have dragged these two buttons for the action as:

@IBAction func btnClicked(sender: UIButton) {
let tag = sender.tag
self.clearPopups()
switch (tag) {
case 1:
self.datePicker.hidden = false
self.datePicker.datePicker.maximumDate = nil
self.datePicker.datePicker.minimumDate = nil

if(self.healthActionPlanCondition.dateClosed != nil)
{
self.datePicker.datePicker.maximumDate = self.healthActionPlanCondition.dateClosed
}
if(self.healthActionPlanCondition.nextProgressReviewDate != nil)
{
self.datePicker.datePicker.setDate(self.healthActionPlanCondition.nextProgressReviewDate, animated: true)
}
self.selectedBtn = self.btnProgressDate
case 2:
self.datePicker.hidden = false
if(self.healthActionPlanCondition.nextProgressReviewDate != nil)
{
self.datePicker.datePicker.minimumDate = self.healthActionPlanCondition.nextProgressReviewDate
}

if(self.healthActionPlanCondition.dateClosed != nil)
{
self.datePicker.datePicker.setDate(self.healthActionPlanCondition.dateClosed, animated: true)
}
self.datePicker.datePicker.maximumDate = nil
self.selectedBtn = self.btnClosedDate
default:
print("Proper btn not found")
}


}


But every time I clicked to any of the buttons default case will be executed. I am totally new to swift. What am I doing wrong here??

Answer

Instead of using tag, In your action method can use IBOutlet of UIButton that you have created like this way.

@IBAction func btnClicked(sender: UIButton) {
    self.clearPopups()
    if sender == btnProgressDate {
        self.datePicker.hidden = false
        self.datePicker.datePicker.maximumDate = nil
        self.datePicker.datePicker.minimumDate = nil

        if(self.healthActionPlanCondition.dateClosed != nil)
        {
            self.datePicker.datePicker.maximumDate = self.healthActionPlanCondition.dateClosed
        }
        if(self.healthActionPlanCondition.nextProgressReviewDate != nil)
        {
            self.datePicker.datePicker.setDate(self.healthActionPlanCondition.nextProgressReviewDate, animated: true)
        }
        self.selectedBtn = self.btnProgressDate
    }
    else if sender == btnClosedDate {
        self.datePicker.hidden = false
        if(self.healthActionPlanCondition.nextProgressReviewDate != nil)
        {
            self.datePicker.datePicker.minimumDate = self.healthActionPlanCondition.nextProgressReviewDate
        }

        if(self.healthActionPlanCondition.dateClosed != nil)
        {
            self.datePicker.datePicker.setDate(self.healthActionPlanCondition.dateClosed, animated: true)
        }
        self.datePicker.datePicker.maximumDate = nil
        self.selectedBtn = self.btnClosedDate
    }
    else {
        print("Proper btn not found")
    }
}    
Comments