4

I use SDWebImage in my project but I was wondering if there is a way to set the image to the background of a button?

user5432778
  • 121
  • 1
  • 14

5 Answers5

4

You just need to import this class of SDWebImage

#import "SDWebImage/UIButton+webCache.h"

and UIButton+webCache this class is Category class so you can set your button background image like this,

[yourBTN sd_setBackgroundImageWithURL:[NSURL URLWithString:@"urlString.png"] forState:UIControlStateNormal placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
Mayank Patel
  • 3,868
  • 10
  • 36
  • 59
4

Swift 3

Been stuck for hours . Mayank Patel's answer is correct.

button.sd_setBackgroundImage(with: URL(string:url), for: .normal)
Ugo Marinelli
  • 989
  • 1
  • 11
  • 18
3
SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadImageWithURL:imageURL
                  options:0
                 progress:^(NSInteger receivedSize, NSInteger expectedSize) {
                     // progression tracking code
                 }
                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
                     if (image) {
                         // do something with image
                        [button setBackgroundImage:image forState:UIControlStateNormal];


                     }
                 }];
Charmi Gheewala
  • 818
  • 7
  • 9
2

There are method for this in SDWebImage

Import #import <SDWebImage/UIButton+WebCache.h>

Use any of this method:

- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state;
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder;
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options;
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state completed:(SDWebImageCompletedBlock)completedBlock;
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletedBlock)completedBlock;
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock;
iVarun
  • 6,496
  • 2
  • 26
  • 34
0

The following is working for me

cell.bProfileImage.sd_setBackgroundImage(with: URL(string:
individualChatsListArray[indexPath.row].profile_image), for:
UIControl.State.normal, placeholderImage: UIImage(named:
"default_profile"), options: SDWebImageOptions(rawValue: 0)) { (image,
error, cache, url) in

}
DragonFire
  • 3,722
  • 2
  • 38
  • 51