Store image URLs by state in the UIButton category

This commit is contained in:
Klaas Pieter Annema 2013-11-29 11:56:47 -05:00
parent 67ed774c0c
commit b9389350cb
2 changed files with 42 additions and 0 deletions

View File

@ -14,6 +14,18 @@
*/
@interface UIButton (WebCache)
/**
* Get the current image URL.
*/
- (NSURL *)currentImageURL;
/**
* Get the image URL for a control state.
*
* @param state Which state you want to know the URL for. The values are described in UIControlState.
*/
- (NSURL *)imageURLForState:(UIControlState)state;
/**
* Set the imageView `image` with an `url`.
*

View File

@ -9,10 +9,27 @@
#import "UIButton+WebCache.h"
#import "objc/runtime.h"
static char imageURLStorageKey;
static char operationKey;
@implementation UIButton (WebCache)
- (NSURL *)currentImageURL;
{
NSURL *url = self.imageURLStorage[@(self.state)];
if (!url) {
url = self.imageURLStorage[@(UIControlStateNormal)];
}
return url;
}
- (NSURL *)imageURLForState:(UIControlState)state;
{
return self.imageURLStorage[@(state)];
}
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state
{
[self setImageWithURL:url forState:state placeholderImage:nil options:0 completed:nil];
@ -37,6 +54,8 @@ static char operationKey;
- (void)setImageWithURL:(NSURL *)url forState:(UIControlState)state placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options completed:(SDWebImageCompletedBlock)completedBlock {
[self cancelCurrentImageLoad];
self.imageURLStorage[@(state)] = url;
[self setImage:placeholder forState:state];
if (url) {
@ -112,4 +131,15 @@ static char operationKey;
}
}
- (NSMutableDictionary *)imageURLStorage;
{
NSMutableDictionary *storage = objc_getAssociatedObject(self, &imageURLStorageKey);
if (!storage) {
storage = [NSMutableDictionary dictionary];
objc_setAssociatedObject(self, &imageURLStorageKey, storage, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
return storage;
}
@end