setBackgroundimage in UIButton using SDWebimage
I totally agree with @CRDave, but if you have to make use of the UIImageView methods for something like setImageWithPreviousCachedImageWithURL (which as of writing isn't part of the UIButton category) then don't set the button background in the completion block otherwise your placeholder or progressive loading won't work. Rather set it like this:
UIImageView *temp = [[UIImageView alloc] init];
[temp sd_setImageWithPreviousCachedImageWithURL:[NSURL URLWithString:stringUrl] andPlaceholderImage:[UIImage imageNamed:@"loading.png"] options:SDWebImageRetryFailed progress:^(NSInteger receivedSize, NSInteger expectedSize) {
//Nothing.
} completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
//Nothing.
}];
[btnTheButton setBackgroundImage:temp.image forState:UIControlStateNormal];
There are method for this in SDWebImage : SDWebImage / SDWebImage / UIButton+WebCache.h
Import this file in your class:
#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:(SDWebImageCompletionBlock)completedBlock;
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder completed:(SDWebImageCompletionBlock)completedBlock;
- (void)sd_setBackgroundImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletionBlock)completedBlock;
You can directly set image to UIButton using SDWebImage
#import <SDWebImage/UIButton+WebCache.h>
[btnProfilePic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"IMAGE_URL_HERE"]]] forState:UIControlStateNormal];
Or using block
[btnProfilePic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"IMAGE_URL_HERE"]]] forState:UIControlStateNormal placeholderImage:UIImage imageNamed:@"placeholderImage.png"] completed:
^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
}];