Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

swift - Change the color of UIButton in IBOutletCollection

I have an IBOutletCollection of UIButton:

@IBOutlet var buttons: [UIButton]!

and a function for a tap:

@IBAction func button_Tap(_ sender: UIButton) {

    for button in buttons {
        if button.tag == sender.tag { button.backgroundColor = .blue }
        else {button.backgroundColor = .white}

    }
}

The outlets are connected in a storyboard.

I need to change the color of the buttons on a button tap. When tap on the first button, it should turn to the blue color and other buttons should be white.

My code does not work correctly. When I tap on the button it turns blue color. But when I tap on another button, the first button does not change the color to white.

Can someone help me to solve this problem? Thanks.

Update:

I also have this code in class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource:

let cellIdentifiers:[String] = ["FirstPercentCell", "SecondPercentCell", "ThirdPercentCell", "FourthPercentCell", "FifthPercentCell"]

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return cellIdentifiers.count
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let collectionCell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifiers[indexPath.item], for: indexPath)
    return collectionCell
}

So maybe the problem in this part?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Try this code:

@IBOutlet var buttons: [UIButton]!
var lastTappedButton: UIButton?

@IBAction func button_Tap(_ sender: UIButton) {

    for button in buttons {
        if let lastTappedButton = lastTappedButton, lastTappedButton != sender {
            button.backgroundColor = .white
        }
        if button.tag == sender.tag { 
            button.backgroundColor = .blue 
            lastTappedButton = button
        }
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...