1

I have 2 buttons in header on CollectionViewController. When i tap on one of them i'm changing an image of this buttons using UIControlState -> .normal .selected.

override func viewDidLoad() {
    super.viewDidLoad()
    collectionView.delegate = self
    collectionView.dataSource = self

    engSwitchButton.setImage(#imageLiteral(resourceName: "abc"), for: .normal)
    geoSwitchButton.setImage(#imageLiteral(resourceName: "abg"), for: .normal)
    engSwitchButton.setImage(#imageLiteral(resourceName: "abc2"),for: UIControlState.selected)
    geoSwitchButton.setImage(#imageLiteral(resourceName: "abg2"), for: UIControlState.selected)


    engSwitchButton.tag = Language.english.rawInt
    geoSwitchButton.tag = Language.georgian.rawInt
}



@IBAction func languageSwitchTapped(_ sender: UIButton) {

    sender.isSelected = !sender.isSelected



    selectedLanguage = Language(rawInt: sender.tag)!
    collectionView.reloadData()
}

I want the button which i tapped first, get back to .normal state when i'm changing state of 2d button with tapping on it.

SunCode
  • 43
  • 10

2 Answers2

0

To change a button image on tap you should use the UIControlState.highlighted.

So change:

engSwitchButton.setImage(#imageLiteral(resourceName: "abc2"),for: UIControlState.selected)
    geoSwitchButton.setImage(#imageLiteral(resourceName: "abg2"), for: UIControlState.selected)

To this:

engSwitchButton.setImage(#imageLiteral(resourceName: "abc2"),for: UIControlState.highlighted)
    geoSwitchButton.setImage(#imageLiteral(resourceName: "abg2"), for: UIControlState.highlighted)
torinpitchers
  • 1,282
  • 7
  • 13
  • when I use .highlighted it just works during tapping. Thats why I'm using .selected, because when i tap button 1 it must stay .selected and when i tap button 2 i want it to become .selected and button 1 must get back to .normal – SunCode Nov 16 '16 at 18:31
0
@IBAction func yourFirstButton(_ sender: Any) {
    firstButton.setImage(UIImage(named: "yourButtonPressedImage")!, for: .normal)
    secondbutton.setImage(UIImage(named: "yourNormalImage")!, for: .normal)


}

and in your second buttons @IBAction method just switch the images for the buttons

 @IBAction func yourSecondButton(_ sender: Any) {
     secondButton.setImage(UIImage(named: "yourButtonPressedImage")!, for: .normal)
     firsBbutton.setImage(UIImage(named: "yourNormalImage")!, for: .normal)


 }
Sagar V
  • 12,158
  • 7
  • 41
  • 68
Anonymous
  • 168
  • 1
  • 12
  • the problem im facing right now (as I literally just implemented this) is setting it as the default image once I press the button – Anonymous Jul 19 '17 at 14:31