1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| #define GlobalQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0) #define MainQueue dispatch_get_main_queue() #import "ViewController.h"
@interface ViewController () @property (weak, nonatomic) IBOutlet UIButton *button;
@end
@implementation ViewController
//需要设置按钮的image和backgroundImage,建议先把按钮类型改为custom,才能保证设置成功 -(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event { dispatch_sync(GlobalQueue, ^{ //1-子线程下载图片 NSURL *url=[NSURL URLWithString:@"https://img1.baidu.com/it/u=2519912129,4264910682&fm=253&fmt=auto&app=138&f=JPEG"]; NSData *data=[NSData dataWithContentsOfURL:url]; UIImage *image=[UIImage imageWithData:data]; //2-回到主线程设置图片 dispatch_async(MainQueue, ^{ [self.button setImage:image forState:UIControlStateNormal]; }); }); } @end
|