iOS — UIButton best way to handle “selected” and “unselected” Image

In your app, if you want to make the images changes for selected and unselected state, I see lot of people are doing in this way.

func myButtonTapped(){
  if myButton.isSelected == true {
    myButton.isSelected = false
    myButton.setImage(UIImage(named : "unselectedImage"), forState: UIControlState.Normal)
  }else {
    myButton.isSelected = true
    myButton.setImage(UIImage(named : "selectedImage"), forState: UIControlState.Normal)
  }
}

But there is much efficient way available in the UIButton to do the same thing. Do the declaration in the ViewController or where ever you want to create a button.

for Swift

let myButton = UIButton(frame : CGRectMake (10, 300, 100, 40))
myButton.setTitle("My Button", forControlState : UIControlState.Normal)
myButton.setImage(UIImage(named : "unselectedImage"), forState: UIControlState.Normal)
myButton.setImage(UIImage(named : "selectedImage"), forState: UIControlState.Selected)
myButton.addTarget(self, action: #selector(myButtonTapped), forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(myButton)

for Objectice-C

UIButton *myButton = [[UIButton alloc] initWithFrame:CGRectMake(10, 300, 100, 40)];
[myButton setTitle:@"My Button" forControlState : UIControlStateNormal];
[myBytton setImage:[UIImage imageNamed:@"unselectedImage"] forState : UIControlStateNormal];
[myBytton setImage:[UIImage imageNamed:@"selectedImage"] forState : UIControlStateSelected];
[myButton addTarget:self action:@selctor(myButtonTapped) forControlEvents:UIControlEventsTouchUpInside];
[self.view addSubview:myButton];

Then in the selector method just do the selection code. Whenever the button is switched to the selected state, it will be automatically changes the images.

for Swift

func myButtonTapped(){
  if myButton.isSelected == true {
    myButton.isSelected = false
  }else {
    myButton.isSelected = true
  }
}

for Objective-C

- (void)myButtonTapped(){
  if (myButton.isSelected ==  true) {
    myButton.isSelected = NO;
  }else {
    myButton.isSelected = YES;
  }
}

Thanks ! Keep Watching http://medium.com/hackthecode for more exciting tips and tricks on iOS.