开发者社区> 问答> 正文

关于下载和设置UIImage不在主线程中 的问题

从web服务器中添加一个图片。怎么设置它不在主线程上?我想要视图先加载,然后图片加载。这样用户在体验时不会感到很慢。

就是不知道怎么加到代码中。

NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:mainImageUrl]];
UIImage *image = [ [UIImage alloc] initWithData:imageData];

UIView *v = [ [UIView alloc] initWithFrame:CGRectMake(10, 150, 300, 180)];
UIImageView *iv = [ [UIImageView alloc] initWithFrame:CGRectMake(0, 10, 300, 180)];
[iv setImage:image];   
[_scrollView addSubview:v];
[v addSubview:iv];

我想到可以加到线程中的:

dispatch_async( dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Add code here to do background processing
//
//
dispatch_async( dispatch_get_main_queue(), ^{
    // Add code here to update the UI/send notifications based on the
    // results of the background processing
});
});

展开
收起
爵霸 2016-03-17 11:35:29 1706 0
1 条回答
写回答
取消 提交回答
  • 现在有不少处理这种情况的解决方案。有一些第三方的库可以实现这种的异步图片加载,你只需要关注自己的逻辑就可以了。如:EGOImageView ,也可以自己到code4app.com这个网站上去搜一下。

    2019-07-17 19:04:58
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载