IOS developed for UIButton Add Category method load network picture
Using the GCD thread queue implementation
The project is as follows:
Uibutton+webcache.h
#import <UIKit/UIKit.h>
To add a category method to a button
@interface UIButton (Webcache)
-(void) Xr_setbuttonimagewithurl: (NSString *) urlstr;
@end
Uibutton+webcache.m
#import "Uibutton+webcache.h"
@implementation UIButton (Webcache)
-(void) Xr_setbuttonimagewithurl: (NSString *) Urlstr {
Nsurl * url = [Nsurl urlwithstring:urlstr];
Download picture data according to the URL of the picture
dispatch_queue_t xrqueue = dispatch_queue_create ("LoadImage", NULL); To create a GCD thread queue
Dispatch_async (Xrqueue, ^{
Download Images asynchronously
UIImage * img = [UIImage imagewithdata:[nsdata datawithcontentsofurl:url];
Main thread Refresh UI
Dispatch_async (Dispatch_get_main_queue (), ^{
[Self setimage:img forstate:uicontrolstatenormal];
});
});
}
@end
#import <UIKit/UIKit.h>
@interface Xrviewcontroller:uiviewcontroller
@property (Weak, nonatomic) Iboutlet UIButton *imgbtn;
@end
#import "XRViewController.h"
#import "Uibutton+webcache.h"
@interface Xrviewcontroller ()
@end
@implementation Xrviewcontroller
-(void) viewdidload
{
[Super Viewdidload];
Additional setup after loading the view, typically from a nib.
}
-(Ibaction) LOADIMG: (ID) Sender {
[Self loadimage];
}
-(void) LoadImage {
[_imgbtn xr_setbuttonimagewithurl:@ "http://img3.3lian.com/2014/c2/66/d/56.jpg"];
}
-(void) didreceivememorywarning
{
[Super didreceivememorywarning];
Dispose of any resources the can be recreated.
}
@end
:
IOS Development for UIButton Add Category method load network picture