Search code examples
iosswiftuisegmentedcontrol

Swift UISegmentedControl if change


How can I create check all time when UISegmentedControl was cheged to another case ?

Example

I create UISegmentedControl:

var type = 0

 @objc func change(sender: UISegmentedControl) {
    switch sender.selectedSegmentIndex {
      case 0:
        type = 0
      case 1:
        type = 1
      case 2:
        type = 2
      case 3:
        type = 3
      default:
        type = 2
    }

And I have func when I need to check and change data when change button in SegmentedControl

func Example() {

  if type == 0 {
    print("case 0")
  } else if type == 1 {
    print("case 1")
  } else if type == 2 {
    print("case 2")
  } else if type == 3 {
    print("case 3")
  }
}

Solution

  • Don't check by calling a function. Move the code to be executed after the type changes into the action

    @objc func change(sender: UISegmentedControl) {
         switch sender.selectedSegmentIndex {
         case 0:
             type = 0
             print("case 0")
         case 1:
             type = 1
             print("case 1")
         case 3:
             type = 3
             print("case 3")
         default:
             type = 2
             print("case 2")
        }
    }
    

    func Example() {
        if type == 0 {
           print("case 0")
        } else if type == 1 {
           print("case 1")
        } else if type == 2 {
           print("case 2")
        } else if type == 3 {
           print("case 3")
        }
    }