16

SDWebImageを使ってUIButtonの背景画像を設定したいです。

コード :-

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

ありがとう

4

6 に答える 6

36

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;
于 2013-10-31T12:40:45.860 に答える
4

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) {

    }];
于 2015-10-20T11:15:37.190 に答える
2

私は@CRDaveに完全に同意しますが、setImageWithPreviousCachedImageWithURL(執筆時点ではUIButtonカテゴリの一部ではありません)のようなものにUIImageViewメソッドを使用する必要がある場合は、完了ブロックにボタンの背景を設定しないでください。プレースホルダーまたはプログレッシブ ロードは機能しません。むしろ、次のように設定します。

    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];
于 2014-08-19T13:36:38.993 に答える
1
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];       
            }];
于 2013-10-31T10:57:20.673 に答える