How can I use a custom image for a Swift button but still control the text separately?

Below is a simple code patch I use to create a custom button, am new at this. I noticed the text does not appear and am wondering what the proper method is for making the text appear?

func makeButton (vControl: ViewController, action: Selector) {
    
    let myButtonImage = UIImage(named: "Picture1.png")
    let imageScale = myButtonImage!.size.width / myButtonImage!.size.height
    let wwidth = vControl.self.view.bounds.width
    
  
    
    let button = CreateButton(frame: CGRect(x: 100, y: 100, width: (myButtonImage?.size.width)!/3, height: (myButtonImage?.size.height)!/3))
    button.setImage(myButtonImage, for: .normal)

    button.backgroundColor = .clear
    button.setTitleColor(.black, for: .normal)
    button.setTitle("Test Button", for: .normal)
    button.addTarget(vControl, action: action, for: .touchUpInside)

    vControl.view.addSubview(button)
    button.center = vControl.view.center
}

Answered by SergioDCQ in 692406022

So I modified the code as such:

//    button.setImage(scaledImage, for: .normal)
    button.setBackgroundImage(scaledImage, for: .normal)

And that does work. But am unsure if I have to do anything with the .setImage method

Accepted Answer

So I modified the code as such:

//    button.setImage(scaledImage, for: .normal)
    button.setBackgroundImage(scaledImage, for: .normal)

And that does work. But am unsure if I have to do anything with the .setImage method

What do you want to get ? Text inside the image or below ? If so, read here:

https://developer.apple.com/documentation/uikit/uibutton

But in your case, that's normal: the image was hiding the text. If you set as background, then text appear.

You could also:

  • set alpha for the image to 0.5: text would appear dimmed
  • add a label atop the image with the text of the button (its title).

Problem may be the visual effect when you push button.

It would help to see your code of createButton (starting with lowercase !)

It works now with me only setting the background image. But can I leave setIamge blank? Or do I have to set it to nil?

How can I use a custom image for a Swift button but still control the text separately?
 
 
Q