IOS Development for UIButton Add Category method load network picture

Source: Internet
Author: User
Tags uikit

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.