在UIPageViewController过渡期间加载图像

时间:2017-11-21 04:54:49

标签: ios objective-c uipageviewcontroller

我有UIPageViewController课程,我收集所有图片网址(nTempElements)并将其传递给ContentViewController,其中图像加载发生。当用户向后或向前滚动时,它始终将第一个视图控制器图像显示为占位符,直到加载滚动页面图像。

如果我删除dispatch_async中的ContentViewController,则此问题不再有效,但对触摸事件的响应稍有不足,因为图像加载发生在主线程上。

针对此问题的任何建议或解决方案?

PageContentViewController.m

- (PageContentViewController *)viewControllerAtIndex:(NSUInteger)index
{    
    if (([self.nTempElements count] == 0) || (index >= [self.nTempElements count])) {
        return nil;
    }

    // Create a new view controller and pass suitable data.
    PageContentViewController *pageContentViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ContentViewController"];
    pageContentViewController.imageURL = self.nTempElements[index];
    return pageContentViewController;
}

ContentViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *url = [NSURL URLWithString:self.imageURL];
        NSData *data = [NSData dataWithContentsOfURL:url];
        UIImage* image = [[UIImage alloc]initWithData:data];

        dispatch_async(dispatch_get_main_queue(), ^{
            [self.newsImageView setImage:image];
        });
    });
}

1 个答案:

答案 0 :(得分:0)

可以帮助遵循此代码!!

NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:self.imageURL completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (data) {
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{

                    self.newsImageView.image = image;
            });
        }
    }
}];
[task resume];