How to change button image in swift?

后端 未结 8 2085
一生所求
一生所求 2021-02-10 04:16

I am working on an app which has a button. The button has no text, image or background.

So what I want to do is to give it an image in the viewDidLoad function.

相关标签:
8条回答
  • 2021-02-10 04:44

    There's one simple solution:

    @IBOutlet var tapButton: UIButton!{
    didSet{
    let image = UIImage(named: imageColor[randNum])
    tapButton.setImage(image, forState: UIControlState.Normal)
    }
    

    Besides that, in the Attribute Inspector, Set Button type to 'Custom'

    0 讨论(0)
  • 2021-02-10 04:46

    First I would put the image you wanted inside the Assets.xcassets folder. Just drag it in. Then you can call it whatever you want by double-clicking on it. Lets say that it is called "redTap".

    For code you would put:

    @IBOutlet var tapButton: UIButton!
    
    override func viewDidLoad() {
    
        super.viewDidLoad()
    
        let redTapImage = UIImage(named: "redTap")
        tapButton.setImage(redTapImage, forState: UIControlState.Normal)
    }
    
    0 讨论(0)
提交回复
热议问题