简体   繁体   中英

How to get a button image to change to a different image when selected programmatically?

I have a button that changes images when different items from an array are displayed in a label. I want the button image to change to a different one when the button is selected. How do I do this programmatically? I tried button1.setImage(UIImage(named: "GreenHeart"), for: .selected), but that doesn't seem to work(Image just stays at Heart). For some reason if I use.highlighted instead of.selected everything works just fine (I can see the GreenHeart Image). Not sure if that helps at all but I'm new to coding so I thought I'd add it here for more support.

import UIKit
class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
}

@IBOutlet weak var quotesLabel: UILabel!
var firstQuote = -1
var quotes = ["The best time to plant a tree was 20 years ago - The next best time is today - Unknown",
                            "Everytime you spend money, you're casting a vote for the type of world you want - Anna Lappe",
                            "Buy less, choose well, make it last - Vivienne Westwood",
                            "The future depends on what we do in the present - Mahatma Gandhi",
]


@IBAction func nextButton(_ sender: Any) {
   
    if firstQuote < quotes.count{
    firstQuote = (firstQuote + 1) % quotes.count
    quotesLabel.text = quotes[firstQuote]
    }
    
    let quote1 = "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"
    let quote2 = "Everytime you spend money, you're casting a vote for the type of world you want - Anna Lappe"
  
    let quote = quotesLabel.text

        let view1 = UIView()
        view.addSubview(view1)
        view1.frame = CGRect(x: 100, y: 500, width: 200, height: 100)
        view1.backgroundColor = .clear
        let button1 = UIButton(type: .custom)
        button1.setImage(UIImage(named: "Heart"), for: .normal)
        button1.setImage(UIImage(named: "GreenHeart"), for: .selected)
        
        view1.addSubview(button1)
        button1.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        button1.isHidden = true
    
        if quote == quote1{
                button1.isHidden = false
            } else {
                button1.isHidden = true
            }
    
        let button2 = UIButton(type: .custom)
        button2.setImage(UIImage(named: "GreenHeart"), for: .normal)
        view1.addSubview(button2)
        button2.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
        button2.isHidden = true

        if quote == quote2{
            button2.isHidden = false
        } else {
            button2.isHidden = true
        }
}


}

First problem is you are creating a new View and button every time you click on the button. You just need to create it once and to do that, you need to move that part of code into viewDidLoad().

After that if you want to change the image of your button whenever you click to different one, you can create a variable:

var isSelected: Bool = false

Inside nextButton() method, toggle the boolean value.

isSelected =.isSelected.

This means, if isSelected is true, it will be false. If it's false, it will be true.

And after that, you can check the boolean value if it's true or not and change the image regarding to boolean value.

button1.setImage(UIImage(name: isSelected? "Heart": "GreenHeart"), for: .normal)

If isSelected is true, Heart image will be displayed and if it's false, GreenHeart will be displayed.

@IBOutlet weak var quotesLabel: UILabel!

private let button1 = UIButton(type: .custom)
private var isSelected: Bool = false

var firstQuote = -1
var quotes = ["The best time to plant a tree was 20 years ago - The next best time is today - Unknown",
              "Everytime you spend money, you're casting a vote for the type of world you want - Anna Lappe",
              "Buy less, choose well, make it last - Vivienne Westwood",
              "The future depends on what we do in the present - Mahatma Gandhi",
]
override func viewDidLoad() {
    super.viewDidLoad()
    setupUI()
}

private func setupUI() {
    let view1 = UIView()
    view.addSubview(view1)
    view1.frame = CGRect(x: 100, y: 500, width: 200, height: 100)
    view1.backgroundColor = .clear
    
    view1.addSubview(button1)
    button1.frame = CGRect(x: 0, y: 0, width: 50, height: 50)
    
    // button1.isHidden = true
}

@IBAction func nextButton(_ sender: UIButton) {
    
    if firstQuote < quotes.count{
        firstQuote = (firstQuote + 1) % quotes.count
        quotesLabel.text = quotes[firstQuote]
        }
   
    isSelected = !isSelected

    let quote1 = "The best time to plant a tree was 20 years ago - The next best time is today - Unknown"
    let quote2 = "Everytime you spend money, you're casting a vote for the type of world you want - Anna Lappe"
    let quote = quotesLabel.text

    button1.setImage(UIImage(name: isSelected ? "Heart": "GreenHeart"), for: .normal)
    /*
    if quote == quote2{
        button1.isHidden = false
    } else {
        button1.isHidden = true
    } */
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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