简体   繁体   English

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

[英]I want to change UIButton Image when tapped on it

I have 2 buttons in header on CollectionViewController. 我在CollectionViewController的标题中有2个按钮。 When i tap on one of them i'm changing an image of this buttons using UIControlState -> .normal .selected. 当我点击其中一个时,我正在使用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. 我想要首先点击的按钮,当我通过点击它改变2d按钮的状态时,回到.normal状态。

To change a button image on tap you should use the UIControlState.highlighted . 要在点击时更改按钮图像,您应该使用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)
@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方法只需切换按钮的图像

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


 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM