将图片加载到UIButton中时,图片不会显示

时间:2013-05-26 09:10:10

标签: ios objective-c cocoa-touch

我一直在使用这段代码并且工作正常:

NSData * imageData = [[NSData alloc] initWithContentsOfURL: [NSURL URLWithString: currentMovie.trailerThumb]];        
[button setBackgroundImage:[UIImage imageWithData:imageData] forState:UIControlStateNormal];
[_moviesScroll addSubview:button];

现在我正在尝试使用AFNetworking加载图片:

UIImageView *testMe = [[UIImageView alloc]init];
[testMe setImageWithURL:[NSURL URLWithString:currentMovie.trailerThumb] placeholderImage:[UIImage imageNamed:@"placeHolder.png"]];        
[button setBackgroundImage:testMe.image forState:UIControlStateNormal];
[_moviesScroll addSubview:button];

我得到了占位符图片,但原始图片不会显示。

我尝试过这样的事情: 我将插座连接到IB中的imageView并添加了以下代码:

[_test setImageWithURL:[NSURL URLWithString:@"https://www.url.com/pic.png"] placeholderImage:[UIImage imageNamed:@"placeHolder.png"]];

图像显示正常。但如果我这样做:

[button setBackgroundImage:_test.image forState:UIControlStateNormal];

再次,只是占位符会显示。

2 个答案:

答案 0 :(得分:1)

我最终使用了一个添加了here的用户的提交。 有了这个提交,就像

一样简单
[button setImageWithURL:[NSURL URLWithString: currentMovie.trailerThumb] placeholderImage:[UIImage imageNamed:@"placeHolder.png"] forState:UIControlStateNormal];

答案 1 :(得分:0)

试试这个:

NSURL * photoUrl = [NSURL URLWithString:@"https://www.url.com/pic.png"];

                NSURLRequest*request = [NSURLRequest requestWithURL:photoUrl];

                __weak typeof(UIImageView) *weak_testImage = _testImage;



                [_testImage setImageWithURLRequest:request placeholderImage:[UIImage imageNamed:@"placeHolder.png"] success:^(NSURLRequest *request, NSHTTPURLResponse *response, UIImage *image) {

                    weak_testImage.image = image;

                    [button setBackgroundImage:_testImage.image forState:UIControlStateNormal];



                } failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error) {



                }];