一个小坑,关于TabBarItem.image图的设置,如果需要从网上下载图再赋值,必须先给它赋值一张默认的图 才能在下载完成的block中修改成功,整了我一上午!
如下:
self.homeVC.tabBarItem.image = [[UIImage imageNamed:defaultItem.icon] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
self.homeVC.tabBarItem.selectedImage = [[UIImage imageNamed:defaultItem.selectedIcon] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
//使用SDWebImage来下载及缓存
[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:responseItem.icon] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (!error && finished) {
self.homeVC.tabBarItem.image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
}];
[[SDWebImageManager sharedManager] downloadImageWithURL:[NSURL URLWithString:responseItem.selectedIcon] options:0 progress:nil completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished, NSURL *imageURL) {
if (!error && finished) {
self.homeVC.tabBarItem.selectedImage = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
}
}];
经试验,虽然后面block中会给tabBarItem.image赋值,但如果前面先不赋个默认值,图片会无法显示的,所以前面这句一定不能掉:self.homeVC.tabBarItem.image = [[UIImage imageNamed:defaultItem.icon] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
另外
不借助SDWebImage,也可以使用下方法异步下载图片显示(无缓存)
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSString *imageString = @"http://www.easyicon.net/api/resizeApi.php?id=1199824&size=48";
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageString]];
UIImage *image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^{
self.imageView.image = image;
});
});