在UIButton中使用SDWebimage的setBackgroundimage

我想使用SDWebImage来设置UIButton背景图片。

代码: –

[btn.imageView setImageWithURL:[NSURL URLWithString:@"image url here"] placeholderImage:[UIImage imageNamed:@"placeholder"]]; 

谢谢

SDWebImage中有这样的方法: SDWebImage / SDWebImage / UIButton + WebCache.h

在你的课堂上导入这个文件:

 #import <SDWebImage/UIButton+WebCache.h> 

使用任何这种方法:

 - (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; 

您可以使用SDWebImage直接将图像设置为UIButton

 #import <SDWebImage/UIButton+WebCache.h> [btnProfilePic sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"IMAGE_URL_HERE"]]] forState:UIControlStateNormal]; 

或者使用块

 [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) { }]; 

我完全同意@CRDave,但是如果你必须使用UIImageView的方法,像setImageWithPreviousCachedImageWithURL(这是写作不属于UIButton类别的一部分),那么不要在完成块中设置button背景,否则你的占位符或渐进式加载将不起作用。 而是像这样设置:

  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]; 
 UIImageView *imageViewb; [imageViewb setImageWithURL:[NSURL URLWithString:@"image url here"] placeholderImage:[UIImage imageNamed:@"placeholder"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType) { [button setImage: imageViewb.image forState:UIControlStateNormal]; }]; 

如果#import <SDWebImage/UIButton+WebCache.h>没有find,那么我认为你必须使用#import“UIButton + WebCache.h”而不是#import <SDWebImage/UIButton+WebCache.h>

这对我来说很好