On iOS 6 SDK I wrote the following lines of code to display an image inside a button:
NSURL *thumbURL2 = [NSURL URLWithString:@"http://example.com/thumbs/2.jpg"];
NSData *thumbData2 = [NSData dataWithContentsOfURL:thumbURL2];
UIImage *thumb2 = [UIImage imageWithData:thumbData2];
[btn2 setImage:thumb2 forState:UIControlStateNormal];
[self.view addSubview:btn2];
But now with Xcode 5 and iOS 7 this doesn't work. The button doesn't contain the image. The button is filled with blue color.
For swift:
I had the same issue. On my storyboard I had a button without any image.
I would then assign the image in the code.
IOS 7 came and I got a lot of blue images.
The resolution was simple yet confusing. If I assign any image on the storyboard and then change the image at run time it works fine.
You always must specify a starting image on the storyboard even if you are not going to use it.
Using Xcode 9.2 none of the above solutions worked for what I was looking for.
I was looking for a solution that will let me set
.normal
and.selected
UIControlState
images inside the storyboard for their original rendering mode, but, inside the Swift file, no string literals should exist regarding the image names.Basically, inside your code you will get the image you set inside your storyboard for
.normal
state and re-render it as.alwaysOriginal
(Same for.selected
state), then, you will set that image (which is now rendered as original and won't be affected by the tint) for the relevant state (.normal
and.selected
) of yourUIButton
.Here it is:
This way you can set your button image states and if the image name will change, it won't affect your code.
It seems iOS 7 is using the image provided just as an Alpha mask for displaying the button's tint color. Changing the button type to
UIButtonTypeCustom
did the trick for me (thanks user716216!). Setting the image as background doesn't always work if you already have a background image, as was my case.In iOS 13 -- just set the Tint property to White, while keeping the type of the UIButton as Custom
In Swift 4, initialize your
UIButton
and assign uyour image Data as follows: