实际项目中遇到以下问题:需要从服务器加载若干尺寸未知的图片到APP中作为UIButton的资源图片显示。考虑到的解决方案有:正好项目中有在使用SDWebImage,可以更方便的实现异步请求资源、缓存、
在主线程更换图片这些操作,因此决定继续使用SDWebImage 对UIButton的扩展。所以有了以下方案:
2.首先将UIButton 初始化加载到view中,使用
- (void)sd_setImageWithURL:(NSURL *)url forState:(UIControlState)state completed:
(SDWebImageCompletionBlock)completedBlock;
为button设置图片,在回调block中,对button重新设置frame,可以使用较为简洁的代码实现对所有未知尺寸的图片资源的使用。具体实现如下:
__block CGFloat imageHeight = HEIGHT(self.imageScrollView) - 2*margin;
__block CGFloat currentWidth = 0;
for (int i =0;i<[_imageURLs count]; i++) {
NSString *imageURL = [host stringByAppendingString:[_imageURLs objectAtIndex:i]];
UIButton *imageButton =[[UIButton alloc]init];
[imageButton addTarget:self action:@selector(imageButtonOnSelected:) forControlEvents:UIControlEventTouchUpInside];
imageButton.tag = i;
[imageButton sd_setImageWithURL:[NSURL URLWithString:imageURL] forState:UIControlStateNormal completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL){
NSLog(@"%@,%@,%ld,%@",image,error,(long)cacheType,imageURL);
CGRect frame = imageButton.frame;
if (image.size.height<image.size.width) {
frame.size.width = imageHeight;
frame.size.height = frame.size.width/image.size.width*image.size.height;
}
imageButton.frame = frame;
[imageButton setTransform:CGAffineTransformMakeRotation(M_PI/2)];
imageButton.center = CGPointMake(WIDTH(imageButton)/2 +currentWidth, HEIGHT(_imageScrollView)/2);
[_imageScrollView addSubview:imageButton];
currentWidth +=(WIDTH(imageButton) +margin);
imageWidth = WIDTH(imageButton);
[_imageScrollView setContentSize:CGSizeMake(currentWidth, imageHeight)];
}];
}
查看SDWebImage代码可以看到 completedBlock 实在回调主线程,因此可以直接在对调中对UI进行更新。