Alejandrina
Alejandrina

Reputation: 3

How to put an image in a button by code in Swift?

I'm trying to make a menu that depends on the kind of profile the user has, so I'm trying to set an image on the buttons. I did it this way:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var btn1: UIButton!
    @IBOutlet weak var btn2: UIButton!
    @IBOutlet weak var txtNum: UITextField!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }
    @IBAction func btnSend(_ sender: Any) {
        var Num = txtNum.text!
        if Num == "1" {
            btn1.setImage(UIImage(named:"museos.png"), for: .normal)
            btn2.setImage(UIImage(named: "otros.png"), for: .normal)
        } else if Num == "2" {
            btn1.setImage(UIImage(named:"parques.png"), for: .normal)
            btn2.setImage(UIImage(named: "monumentos.png"), for: .normal)
        }
    }  
}

But, once the app runs, it shows me the buttons like this:

screenshot

and I don't know what is happening here. Some help?

Upvotes: 0

Views: 81

Answers (1)

Hamer
Hamer

Reputation: 1383

Remove the .png extensions from your image names.

You can also try changing your button type from system to custom. Setting the image requires using the setImage function.

button.setImage(UIImage(named: "museos"), for: .normal)

Upvotes: 1

Related Questions