skip to Main Content

What is the difference between UIbutton.setImage and changing UIbutton.imageView?

buttonA.imageView?.image = UIImage(named: "name")

buttonA.setImage(UIImage(named: "name"), for: .normal)

When I try to use setImage and then try to get it’s position using frame.origin.x, the position returned are not what I expected and so I used .imageView?.image approach. But when I use that, I observed that clicking on the button changes the image for a brief time before continuing.

2

Answers


    1. the function offers you the ability to set different icons for various states
        setImage(imageNormal, for: .normal) //normal state
        setImage(disabledImage, for: .disabled) //disable UI representation
    
    1. UIButton.imageView according to documentation read-only property https://developer.apple.com/documentation/uikit/uibutton/1624033-imageview
    Login or Signup to reply.
  1. For some clarification…

    If you set the .image property directly:

    buttonA.imageView?.image = UIImage(named: "name")
    

    You have not informed the button class that it has a new image property.

    The same thing applies to setting the title:

    buttonA.titleLabel?.text = "My Title"
    

    That will change the text of the title label, but only until the next UI update… at which point UIKit will use the value assigned via:

    buttonA.setTitle("Button A", for: .normal)
    

    That’s why it’s important to use both .setImage(...) and .setTitle(...) instead of setting the property itself.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search