0

I am trying to set an image to a button. For trying, I added an ImageView and a Button on the Storyboard. I connected both to my view controller.

@IBOutlet weak var testImage: UIImageView!
@IBOutlet weak var testButton: UIButton!

Then I try to fetch image online and set both. After fetching the data,

...
 dispatch_async(dispatch_get_main_queue()) {
    if let image = data {
         self.testButton.setImage(UIImage(data: image), forState: UIControlState.Normal)
         self.testImage.image = UIImage(data: image)
    }
 }

At this point, testImage sets the image just perfect but the testButton is turning into a blue rectangle.

enter image description here

What am I doing wrong?

senty
  • 12,385
  • 28
  • 130
  • 260
  • 1
    Make sure the button is `UIButtonTypeCustom`. On the storyboard you can change its type from System to Custom. – Matt Le Fleur Jan 20 '16 at 17:26
  • 1
    Just for reference - it looks like [someone had a similar problem](http://stackoverflow.com/questions/24243547/swift-how-to-display-image-over-button). – Matt Le Fleur Jan 20 '16 at 17:30
  • @senty study little more about autolayout http://stackoverflow.com/questions/17800288/autolayout-intrinsic-size-of-uibutton-does-not-include-title-insets – Rushi trivedi Jan 22 '16 at 10:43

3 Answers3

3

I had the same problem and switching the button type from System to Custom fixed the problem

0

It's possible the button expanded to the size of the fetched image. That is just a guess on my part but if that is the case you might check the attributes inspector to see if there is an option to have content shrieked to fit or something like that.

If that is what is happening, another option would be to change the size of the image to the size of the button before adding the image to the button.

Don't know if that helped. Good luck!

user2807654
  • 122
  • 1
  • 1
  • 11
0

Had the same problem , fixed it with this code:

self.testButton.setBackgroundImage(image, for: .normal)
ironRoei
  • 2,049
  • 24
  • 45