我想在点击它时更改UIButton图像

时间:2016-11-16 14:15:27

标签: ios swift uibutton uicontrolstate

我在CollectionViewController的标题中有2个按钮。当我点击其中一个时,我正在使用UIControlState更改此按钮的图像 - > .normal。选择。

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()
}

我想要首先点击的按钮,当我通过点击它来改变2d按钮的状态时,回到.normal状态。

2 个答案:

答案 0 :(得分:0)

要更改按钮图像,您应使用UIControlState.highlighted

所以改变:

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

对此:

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

答案 1 :(得分:0)

@IBAction func yourFirstButton(_ sender: Any) {
    firstButton.setImage(UIImage(named: "yourButtonPressedImage")!, for: .normal)
    secondbutton.setImage(UIImage(named: "yourNormalImage")!, for: .normal)


}

并在第二个按钮中@IBAction方法只需切换按钮的图像

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


 }